use*_*805 0 c# lambda delegates
我从Jrista的帖子中回答了以下例子.
找到Twentyone计数
int[] numbers = new[] { 1, 3, 11, 21, 9, 23, 7, 4, 18, 7, 7, 3, 21 };
var twentyoneCount = numbers.Where(n => n == 21).Count();
Run Code Online (Sandbox Code Playgroud)
假设我使用"Func"委托如何获得计数?
我试过(原谅我的语法错误)
var otherway= Func <int> numbers= x => x==21;
Run Code Online (Sandbox Code Playgroud)
您正在使用具有相同签名的匿名委托Func<int, bool>.如果你想使用一种方法,你可以写:
// a method that takes int and returns bool is
// a Func<int, bool> delegate
public bool IsEqualTo21(int x)
{
return (x == 21);
}
Run Code Online (Sandbox Code Playgroud)
然后将其用作:
var twentyoneCount = numbers.Where(IsEqualTo21).Count();
Run Code Online (Sandbox Code Playgroud)