• C#Linq


    概念:“查询”也是一种指令,使用这组指令可以从给定的一个或多个数据源中检索数据,并以指令的形式返回结果。Linq也是一种查询,可以为编程语言提供强大的方便的查询功能,并与其合为一体。

    Linq的强大体现在它的简洁 方便的代码量。比如要筛选出list中一个属性的元素,相对于list就要遍历判断;但是你用linq就只需要一句。但是这也会造成一些问题,导致后期比人维护你的项目造成麻烦(哪有最好的东西呀,双刃剑吧 哈哈)

    From:子句被查询的数据源(相当于for循环)

    Where:子句指定元素所满足的过滤条件(相当于if判断)

    orderby:表现方式(相当于排序方式,升序、降序。。。)

    Select:子句制定查询结果的表现形式,(相当于return)

    下面用代码来说明问题:

    // Linq  Query语句

    int[] numbers = { 12, 23, 34, 45, 56, 67 };
                var numQuery = from num in numbers
                               where num % 2 == 0
                               orderby num ascending // ascending 升序(可省略)
                               select num;
                foreach(var n in numQuery)
                {
                    Console.WriteLine(n);
                }

    // Linq Method语句

    var numMethod = numbers.Where(n => n % 2 == 0).OrderBy(n => n);
                foreach(var n in numMethod)
                {
                    Console.WriteLine(n);
                }

    注意:以上两个语句的代码量相差还是有点大的,Query将每块逻辑分开,而Method将所有逻辑集中于一行来实现。

    into、let关键字

    // Linq  into关键字

    List<Peo> peoList = new List<Peo>();
                peoList.Add(new Peo() { name = "lizhi", city = "shanghai" });
                peoList.Add(new Peo() { name = "linqingxia", city = "beijing" });
                peoList.Add(new Peo() { name = "liuyifei", city = "shanghai" });
                var intoLinq = from num in peoList
                               group num by num.city into groupnum
                               where groupnum.Count() >= 2
                               select new { city = groupnum.Key, number = groupnum.Count() };
                foreach(var i in intoLinq)
                {
                    Console.WriteLine(i.city + "---" + i.number);
                }

    以上示例:into 字面解释意为“打入”,以上事例将遍历proList得到的num筛选出city属性放入groupnum中,这里的groupnam可以看作是一个集合,这个集合存的是city属性。

    // Linq  let关键字

    string[] strings = { "hello world.", "lin qing xia", "wang zu xian" };
                var strs = from s in strings
                           let words = s.Split(' ')
                           from word in words
                           let w = word.ToUpper()
                           select w;
                foreach(var s in strs)
                {
                    Console.WriteLine(s);
                }

    以上示例:将遍历的元素进行处理,并将处理结果存放到words,这里的words也可看作一个集合(可以这样理解,具体自己去发掘 嘿嘿)

  • 相关阅读:
    收藏的日历js算法 很实用
    autofac system.core 的版本问题
    and 组件ui等
    vc相关
    live传264流
    录转rtsphan
    ndk errno
    cpp all记录
    and 录音等+live等
    cmake
  • 原文地址:https://www.cnblogs.com/wmm0105/p/11202205.html
Copyright © 2020-2023  润新知