C# lambda查询带返回值

220 阅读1分钟

问题来源: 《深入理解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 进行输入上述的item,而不是在foreach中加一层判断。


问题简单描述就是:简单来说就是直接在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,解决自己的疑惑

如有哪里讲得不是很明白或是有错误,欢迎指正
如您喜欢的话不妨点个赞收藏一下吧