2

假设我有一个列表,我想检查成员是否都等于“某个字符串”:

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

我认为这会做同样的事情(或者会吗?!):

myList.All("some string".Equals)

但是如果.Equals我不想使用我自己的方法呢?

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

我该如何.Equals替换LessThan16Char


如果方法有第二个参数怎么办(例如lessthan(string Input, Int lessThanVal)

我也很感激网络上任何描述这类事情的文章,谢谢。

4

3 回答 3

6

您可以直接调用它:

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

如果您需要第二个参数,那么您将需要 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);
}
于 2016-04-28T06:07:46.390 回答
2

正如我之前评论的那样,您可以使用myList.All(LessThan16Char).

请记住,这myList.All(LessThan16Char)myList.All(x => LessThan16Char(x)).

第二个创建一个额外的间接。编译器转换x => LessThan16Char(x)为一个方法,该方法获取一个字符串作为输入并调用LessThan16Char它。

您可以看到生成的不同 IL。

1.myList.All(LessThan16Char)

IL_0008:  ldarg.0     
IL_0009:  ldftn       UserQuery.LessThan16Char
IL_000F:  newobj      System.Func<System.String,System.Boolean>..ctor
IL_0014:  call        System.Linq.Enumerable.All

2.myList.All(x=> LessThan16Char(x))

IL_001B:  ldarg.0     
IL_001C:  ldftn       UserQuery.<Main>b__0_0
IL_0022:  newobj      System.Func<System.String,System.Boolean>..ctor
IL_0027:  call        System.Linq.Enumerable.All

和额外生成的方法

<Main>b__0_0:
IL_0000:  ldarg.0     
IL_0001:  ldarg.1     
IL_0002:  call        UserQuery.LessThan16Char
IL_0007:  ret   

通常它们都做同样的事情,但在某些情况下它们可能会有所不同。例如,当您想知道包含传递给 LINQ 查询的方法的类并且您正在传递int.Parse而不是x => int.Parse(x). 第二个是类中的方法,但第一个是框架类。

于 2016-04-28T06:28:36.150 回答
0

您可以编写LessThan16Char为字符串扩展方法:

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

并在您的 lambda 表达式中使用它:

    myList.All(x => x.LessThan16Char());
于 2016-04-28T06:19:51.350 回答