使用Linq查询List中数据的代码

发布时间:2019-12-11编辑:脚本学堂
使用Linq查询List中数据的代码,查询出list中所有女生并且年龄小于18,并按降序排列;查询出list中名字为“王”开头,并且长度为3的学生。

使用Linq查询List中数据的代码,查询出list中所有女生并且年龄小于18,并按降序排列;查询出list中名字为“王”开头,并且长度为3的学生。
有需要的朋友,可以参考学习下。

复制代码 代码如下:

 //1,查询出list中所有女生并且年龄小于18,并按降序排列
 //2,查询出list中名字为“王”开头,并且长度为3的学生
 using System;
 using System.Collections.Generic;
 using System.Linq;
 public class StudyLinq
 {
     public static void Main()
     {
         List<People> list = new List<People>();
         list.Add(new People(){Name = "康熙",Age = 18 ,Sex = "男"});
         list.Add(new People(){Name = "雍正",Age = 20 ,Sex = "男"});
         list.Add(new People(){Name = "乾隆",Age = 18 ,Sex = "男"});
         list.Add(new People(){Name = "王羲之",Age = 23 ,Sex = "男"});
         list.Add(new People(){Name = "武则天",Age = 17 ,Sex = "女"});
         list.Add(new People(){Name = "慈禧",Age = 16 ,Sex = "女"});
         var result = list.Where (p=>p.Age<18 && p.Sex =="女").OrderByDescending(p=>p.Age);
             foreach (People a in result)
             {
                 Console.WriteLine(a.Name + "  "+a.Age);
             }
         var result1 = list.Where (p=>p.Name.StartsWith ("王") && p.Name.Length == 3);
             foreach (People b in result1)
             {
                 Console.WriteLine(b.Name);
             }
     }
     public class People
     {
         public string Name
         {
             get;set;
         }
         public int Age
         {
             get;set;
         }
         public string Sex
         {
             get;set;
         }
     }
 }