LINQ和lambda表达式

发布时间 2023-07-15 18:33:26作者: 阿霖找BUG

LINQ:

select结尾,from开头(from->where->groupby->having->orderby->join->select)

            var tt = from aa in cd
                     select aa.Count();//查询一个值就不用数组

连接数组,join in放在select前面

            var ty = from a1 in wer//用var或者IEnumerable<int>,他是一个集合来着
                     where a1.count > 1
                     join t in werr on a1.q1 equals t.id
                     select new int[] { a1.q1, a1.count, t.id, t.age };//查询多个值要用数组或者实体类

实体类:

    public class mo
    {
        public int q1 { get; set; }
        public int count { get; set; }
    }
            var re = from f in cd
                     from q in f
                     where q > 2
                     select new mo {//实体类
                         q1 = q,
                         count = f.Count()
                     };

lambda表达式:

委托:Func:有返回值的委托;Action:无返回值的委托

Func<int, int> a = (age) => age - 1;//a:函数名;age:参数;age-1:方法体;<int,int>第一个是输入类型,第二个是返回值
unc < (int, int),(int,int,int)> s1 = ns => (ns.Item1,ns.Item2,ns.Item1+ns.Item2);//第一个括号是输入类型,第二个括号是返回值
 Console.WriteLine(a(12));//调用委托

            Action<string> greet = name =>//无返回值所以Action<输入类型>
            {
                string greeting = $"Hello {name}!";
                Console.WriteLine(greeting);
            };

 

LINQ一般和lambda表达式一起用

            int i1 = a.Where(y => y > 2).Count();
            int i2 = a.Where(y => y > 2).Sum();
            IEnumerable<int> v = a.Where(i => i > 1).Take(3);
            IEnumerable<int> w = a.Where(i => i > 2);

循环输出:

            foreach(int[] g in ty)
            {
                Console.WriteLine($"{g[0]},{g[1]},{g[2]},{g[3]}");
            }
            foreach (mo o in re)
            {
                Console.WriteLine(o.q1);
                Console.WriteLine($"数量是:{o.count}");
            }
            foreach (int[] p in io)
            {
                foreach (int op in p)
                {
                    Console.WriteLine(op);
                }
            }