zoukankan      html  css  js  c++  java
  • C# List中写出LINQ类似SQL的语句

    很多时候,从一个关系表中挑出一个我们需要的元素列表采用SQL语句是再容易不过的了,其实C#的List中也可以采用类似的方法,虽然List中集成了Select(), Where()等语句,不过如果你的判断规则较为复杂,或者想要看起来一目了然,以下的方法也是可行的:

    首先假设你有一个类

    public class People
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
    并且有一些初始化语句
    List<People> PeopleList = new List<People>();
    PeopleList.Add(new People() { Name = "Haocheng Wu", Age = 24 });
    PeopleList.Add(new People() { Name = "Haocheng Wu", Age = 25 });
    PeopleList.Add(new People() { Name = "James Wu", Age = 23 });

    你就可以采用下面类似于SQL语句的方法进行select

    List<string> SubPeopleNameList1 = (from people in PeopleList
                                  where people.Name == "Haocheng Wu" && people.Age == 24
                                  select people.Name).ToList<string>();
    当然你也可以用一行代替
     
    List<string> SubPeopleNameList2 = PeopleList.Where(people => people.Name == "Haocheng Wu" && people.Age == 24).Select(people => people.Name).ToList();

    不过显然第一种方法更加一目了然,尤其是当判断条件相当复杂的时候就更加有用了

  • 相关阅读:
    P3180 [HAOI2016]地图
    P2787 语文1(chin1)- 理理思维
    P2221 [HAOI2012]高速公路
    P4137 Rmq Problem / mex
    P3746 [六省联考2017]组合数问题
    P2461 [SDOI2008]递归数列
    P3715 [BJOI2017]魔法咒语
    P3195 [HNOI2008]玩具装箱TOY
    Linux下的strerror是否线程安全?
    bash/shell的字符串trim实现
  • 原文地址:https://www.cnblogs.com/1175429393wljblog/p/4643003.html
Copyright © 2011-2022 走看看