C#高级 10 Linq操作

2024-01-08 13:46:11

1.Linq操作介绍

Linq操作是C#集成的类似于数据库语言的操作,是通过将数据库的表名映射为类,把数据库的列名映射为属性。
Linq查询主要分为3类:
Linq to object(数组、list集合) --内存里面的数据
Linq to sql(查询数据库用的) --在数据库数据
Linq to XML 查询XML文件
这里主要以第一种为例,下面将会直接以代码+注释的方法来展示第一类方式如何使用linQ进行查询。

为方便读者直接复制代码进行运行,就不配置数据库,使用对象的方式来存储数据。下面直接上代码:

在这里插入图片描述
Kongfu.cs内代码如下:

public class Kongfu
{
    public int Id {  get; set; }
    public string Name { get; set; }
    public int Power {  get; set; }
    public override string ToString()
    {
        return string.Format("id:{0}, name:{1}, power:{2}", Id, Name, Power);
    }
}

MartialArtsMaster.cs内代码如下所示:

public class MartialArtsMaster
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age {  get; set; }
    public string Menpai { get; set; }
    public string Kongfu {  get; set; }
    public int Level { get; set; }

    public override string ToString()
    {
        return string.Format("id:{0}, name:{1}, Age:{2}, Menpai:{3}, Kongfu:{4}, Level:{5}",Id,Name,Age,Menpai,Kongfu,Level);
    }
}

program.cs内代码如下所示,使用了masterList 来存储人物信息,kongFuList 来存储武学信息;
同时下面也列举了,Linq查询的表达式和扩展写法、联合查询、集合查询、排序、分组等多种查询方法。

internal class Program
{
    static void Main(string[] args)
    {
        var masterList = new List<MartialArtsMaster>()
        {
            //初始化武林高手
            new MartialArtsMaster() {Id=1,Name="黄蓉",Age=18,Menpai="丐帮",Kongfu="打狗棒法",Level=9},
            new MartialArtsMaster() {Id=2,Name="洪七公",Age=70,Menpai="丐帮",Kongfu="打狗棒法",Level=10},
            new MartialArtsMaster() {Id=3,Name="郭靖",Age=22,Menpai="丐帮",Kongfu="降龙十八掌",Level=10},
            new MartialArtsMaster() {Id=4,Name="任我行",Age=50,Menpai="明教",Kongfu="葵花宝典",Level=1},
            new MartialArtsMaster() {Id=5,Name="东方不败",Age=35,Menpai="明教",Kongfu="葵花宝典",Level=10},
            new MartialArtsMaster() {Id=6,Name="林平之",Age=23,Menpai="华山",Kongfu="葵花宝典",Level=7},
            new MartialArtsMaster() {Id=7,Name="令狐冲",Age=23,Menpai="华山",Kongfu="独孤九剑",Level=10},
            new MartialArtsMaster() {Id=8,Name="梅超风",Age=23,Menpai="桃花岛",Kongfu="九阴真经",Level=8},
            new MartialArtsMaster() {Id=9,Name="黄药师",Age=23,Menpai="桃花岛",Kongfu="弹指神通",Level=10}
        };

        var kongFuList = new List<Kongfu>()
        {
            //初始化功夫
            new Kongfu(){Id=1,Name="打狗棒法",Power=90},
            new Kongfu(){Id=2,Name="降龙十八掌",Power=95},
            new Kongfu(){Id=3,Name="葵花宝典",Power=100},
            new Kongfu(){Id=4,Name="独孤九剑",Power=100},
            new Kongfu(){Id=5,Name="九阴真经",Power=100},
            new Kongfu(){Id=6,Name="弹指神通",Power=100}
        };

        //var res = new List<MartialArtsMaster>();
        //foreach (var temp in masterList)
        //{
        //    if (temp.Level > 8)
        //    {
        //        res.Add(temp);
        //    }
        //}
        //(1)使用LINQ做查询(表达式写法)
        var res1 = from m in masterList
                      //from 后面设置查询集合
                  where m.Level > 8 && m.Menpai == "丐帮"
                  //where后面跟上查询条件
                  select m; //表示m的结果结合返回
                  //select m.Name;  //表示值只返回对象中名字集合

        //(2)扩展写法
        var res2 = masterList.Where(Test1);
		//过滤方法
	    static bool Test1(MartialArtsMaster master)
	    {
	        if (master.Level > 8)
	        {
	            return true;
	        }
	        else 
	        {
	            return false;
	        }
	    }
        //(3)扩展写法
        var res3 = masterList.Where(m => m.Level > 8 &&m.Menpai == "丐帮");
        //(4)联合查询
        var res4 = from m in masterList
                   from k in kongFuList
                   where m.Kongfu == k.Name && k.Power > 90
                   select m;
        //select new { master = m, Kongfu = k };
        //(5)联合查询扩展 masterList.SelectMany(m => kongFuList) 表示 两个对象做联合查询
        var res5 = masterList.SelectMany(m => kongFuList, (m, k) => new { master = m, kongfu = k })
            .Where(x => x.master.Kongfu == x.kongfu.Name && x.kongfu.Power > 90);

        //(6)排序
        var res6 = from m in masterList
                  //from后面设置查询集合
                  where m.Level > 8 && m.Menpai=="丐帮"  
                  //按照多个属性进行排序,如果字段属性相同,就按照第二个属性排序
                  orderby m.Level,m.Age  
                  select m;

        var res7 = from m in masterList
                       //from后面设置查询集合
                   where m.Level > 8 && m.Menpai == "丐帮"
                   //按照多个属性进行排序,如果字段属性相同,就按照第二个属性排序
                   orderby m.Age descending
                   select m;
        //使用OrderByDescending 排序
        var res8 = masterList.Where(m => m.Level > 8 && m.Menpai == "丐帮").OrderByDescending(m => m.Age);

        //ThenBy表示在前面字段相同的情况下使用某个字段排序
        var res9 = masterList.Where(m => m.Level > 8).OrderBy(m => m.Level).ThenBy(m => m.Age);

        //(7)集合联合
        var res10 = from m in masterList
                  join k in kongFuList on m.Kongfu equals k.Name
                  select new { master = m, kongfu = k };

        //(8)分组查询 into groups(把武林高手按照所学功夫分类,看一下那个功夫修炼的人数最多)
        var res11 = from k in kongFuList
                  join m in masterList on k.Name equals m.Kongfu
                  into groups
                  select new { kongfu = k, count = groups.Count()};

        //(9)按自身字段分组 group
        var res12 = from m in masterList
                  group m by m.Menpai
                  into groups
                  //g.Key Key表示是按那个属性分的组
                  select new { count = groups.Count(), groups.Key };


        //(10)量词操作符 any all 判断集合中是否满足某个条件
        bool res13 = masterList.Any(a => a.Menpai == "长留");
        Console.WriteLine("是否存在“长留”门派:{0}",res13);
        bool res14 = masterList.All(a => a.Menpai == "丐帮");
        Console.WriteLine(res14);
        foreach (var temp in res12)
        {
            Console.WriteLine(temp);
        }
        Console.ReadKey();
    }

    
}

文章来源:https://blog.csdn.net/younger_to_older/article/details/135449152
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。