Pimp my LINQ: a learning exercise based upon another post

半世苍凉 提交于 2019-12-04 03:11:16
var result =
        from s in list
        where s.Count(x => x == '=') == 2
        select s.Substring(s.LastIndexOf("-") + 1);

It can also be written using Lambda expressions:

var result =
            list.Where(s => (from c in s where c == '-' select c).Count() == 2).Select(
                s => s.Substring(s.LastIndexOf("-") + 1));

I prefer Lambda expressions over LINQ syntax because of the Fluent interface. IMHO it is more human readable.

I don't think this is an improvement, as it is less readable, but you can do it all in one-line using some of the inbuilt methods in the List class:

list.FindAll(s => s.ToCharArray().
    Where(c => c == '-').Count() ==2).
    ForEach(c => Console.WriteLine(c.Substring(c.LastIndexOf("-") + 1)));

Personally I find this rather horrible, so it's just for interest!

This is pretty nice I think. Partly LINQ.

var result = String.Join("-", inputData.Split('-').Skip(2));

If there can't be any '-' after the first two then this will do (not LINQ):

var result = inputData.Split('-')[2];  //If the last part is NEE-DED then only NEE is returned. And will fail on wrong input
fletcher

I'm a big fan of Lambdas too...

    static void Main(string[] args)  
    {  
        Func<string, char, int> countNumberOfCharsInString = 
             (str, c) => str.Count(character => character == c);

        var list = new List<string>() 
        { "fred-064528-NEEDED1", 
           "xxxx", 
           "frederic-84728957-NEEDED2", 
           "sam-028-NEEDED3", 
           "-----", "another-test" 
        };

        list.Where(fullString => countNumberOfCharsInString(fullString,'-') == 2)
            .ToList()
            .ForEach(s => Console.WriteLine(s.Substring(s.LastIndexOf("-")+1)));

        Console.WriteLine("Press Enter");   
        Console.ReadLine();  
    } 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!