Search code examples
c#.netlinqlambdamethod-group

How apply a method to all list members using very short linq with lambda omitted?


Say I have a List and I want to check if the members are all equal to "some string":

myList.All(v => v.Equals("some string"))

I think this would do the same (or would it?!):

myList.All("some string".Equals)

but what if instead of .Equals I want to use my own method?

public bool LessThan16Char(string input)
{
    return (input.Length < 16);
}

How do I replace .Equals with LessThan16Char?


What if the method has a second parameter (e.g. lessthan(string Input, Int lessThanVal))

I would also appreciate any article on the web that describes these sort of things, Thanks.


Solution

  • You can simply call it directly:

    public Class1()
    {
        var myList = new List<string>();
        var foo = myList.All(LessThan16Char);
    }
    

    if you need a second parameter than you will need the lambda:

    public Class1()
    {
        var myList = new List<string>();
        var foo = myList.All(l=>LessThan16Char(l,16));
    }
    
    
    public bool LessThan16Char(string input, int max)
    {
        return (input.Length < max);
    }