問題來源: 《深入理解C#(第3版)》 11頁
具體如下:
var lists=new List<string>{"111","222","333","1","2"};
foreach(var item in lists.where(x=>x.length>2))
{
Console.WriteLine(item);
}
如果願意,完全可以使用Action
問題簡單描述就是:簡單來說就是直接在where中輸出長度大於2的字符,不需要在在foreach中操作
當看到這句話的時候,心里默認這個自己可以寫出來,當往后翻幾頁后,一直在想着這個問題。心中一直有個疙瘩,於是就想不如實現一下。果不其然發現lambda帶有返回值沒有想象中的那么簡單,於是便有了下面的代碼
static void Main(string[] args)
{
var aaa = new List<string> { "111", "222", "333", "2", "3" };
Func<string, Action<string>, bool> aaafunc = funcTest;
Action<string> action = actionTest;
var result = aaa.Where(s => aaafunc(s, action));
Console.WriteLine($@"篩選后的行數為:{result.Count()}");
Console.WriteLine("hello word");
Console.ReadKey();
}
public static bool funcTest(string s, Action<string> ss)
{
if (s.Length > 2)
{
ss.Invoke(s);
}
return s.Length > 2;
}
public static void actionTest(string s)
{
Console.WriteLine(s);
}
代碼如上,折騰半小時后終於折騰出來了,心中的疙瘩也終於消失了。
然后感謝同事張某人提供的一些思路和介紹。
最后,希望大家也能遇到問題感覺奇怪就直接coding,解決自己的疑惑
如有哪里講得不是很明白或是有錯誤,歡迎指正
如您喜歡的話不妨點個贊收藏一下吧