C#中的LINQ

这篇具有很好参考价值的文章主要介绍了C#中的LINQ。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

一:什么是LINQ

LINQ代表语言集成查询,是.net框架的扩展,它允许我们用SQL查询数据库的方式来查询数据的集合


二:LINQ延迟查询的特性

延迟查询是指查询操作并不是在定义的时候执行,而是在遍历集合中的数据时才执行
因为作为yield迭代器的主体,只有使用foreach遍历执行到MoveNext时才会真正执行方法

using System;
using System.Collections.Generic;
using System.Linq;

class MainClass
{
    static List<Person> personList = new List<Person>()
    {
        new Person(){ Id=1,Name="小明",Age=20,Score=100},
        new Person(){ Id=2,Name="小王",Age=40,Score=80},
        new Person(){ Id=3,Name="小刘",Age=60,Score=60},
    };

    static void Main(string[] args)
    {
        var list = personList.Where((p) => p.Age < 30);

        foreach (var temp in list)
        {
            Console.WriteLine(temp);
        }

        personList.Add(new Person() { Id = 4, Name = "小赵", Age = 15, Score = 100 });

        foreach (var temp in list)
        {
            Console.WriteLine(temp);
        }
    }
}

class Person
{
    public int Id;
    public string Name;
    public int Age;
    public int Score;

    public override string ToString()
    {
        return Id + "," + Name + "," + Age + "," + Score;
    }
}

三:扩展方法用法

Linq有两种写法,查询表达式写法(from.....in.....)和扩展方法写法,两种方法都是相互兼容的,程序编译时会将查询表达式转换为扩展方法,只要实现了IEnumerable的接口就可以使用Linq的扩展方法

——Select:返回指定类型

using System;
using System.Collections.Generic;
using System.Linq;

class MainClass
{
    static List<Person> personList = new List<Person>()
    {
        new Person(){ Id=1,Name="小明",Age=20,Score=100},
        new Person(){ Id=2,Name="小王",Age=40,Score=80},
        new Person(){ Id=3,Name="小刘",Age=60,Score=60},
    };

    static void Main(string[] args)
    {
        var list = personList.Select(p => p.Name);
        var list = personList.Select(p => new { id = p.Id, name = p.Name });

        foreach (var temp in list)
        {
            Console.WriteLine(temp);
        }
    }
}

class Person
{
    public int Id;
    public string Name;
    public int Age;
    public int Score;

    public override string ToString()
    {
        return Id + "," + Name + "," + Age + "," + Score;
    }
}

——Where:查询特定条件

using System;
using System.Collections.Generic;
using System.Linq;

class MainClass
{
    static List<Person> personList = new List<Person>()
    {
        new Person(){ Id=1,Name="小明",Age=20,Score=100},
        new Person(){ Id=2,Name="小王",Age=40,Score=80},
        new Person(){ Id=3,Name="小刘",Age=60,Score=60},
    };

    static void Main(string[] args)
    {
        var list = personList.Where((p) => p.Score >= 80 && p.Age < 50);

        foreach (var temp in list)
        {
            Console.WriteLine(temp);
        }
    }
}

class Person
{
    public int Id;
    public string Name;
    public int Age;
    public int Score;

    public override string ToString()
    {
        return Id + "," + Name + "," + Age + "," + Score;
    }
}

——OfType:查询特定数据类型 

using System;
using System.Collections.Generic;
using System.Linq;

class MainClass
{
    static List<object> objList = new List<object>()
    {
        "test1",
        1,
        1.34f,
        "test2",
    };

    static void Main(string[] args)
    {
        var list = objList.OfType<string>();

        foreach (var temp in list)
        {
            Console.WriteLine(temp);
        }
    }
}

——Join:将一个集合与另一个集合通过指定键合并,返回合并后的集合

using System;
using System.Collections.Generic;
using System.Linq;

class MainClass
{
    static List<Person> personList = new List<Person>()
    {
        new Person(){ Id=1,Name="小明",Age=20,Score=100},
        new Person(){ Id=2,Name="小王",Age=40,Score=80},
        new Person(){ Id=3,Name="小刘",Age=60,Score=60},
    };
    static List<Reward> rewardList = new List<Reward>()
    {
        new Reward(){ Id=1,Score=100,RewardName="奖励1"},
        new Reward(){ Id=2,Score=80,RewardName="奖励2"},
        new Reward(){ Id=3,Score=60,RewardName="奖励3"},
    };

    static void Main(string[] args)
    {
        var list = personList.Join(rewardList, p => p.Score, r => r.Score, (p, r) => new { pList = p, rList = r });

        foreach (var temp in list)
        {
            Console.WriteLine(temp);
        }
    }
}

class Person
{
    public int Id;
    public string Name;
    public int Age;
    public int Score;

    public override string ToString()
    {
        return Id + "," + Name + "," + Age + "," + Score;
    }
}

class Reward
{
    public int Id;
    public int Score;
    public string RewardName;

    public override string ToString()
    {
        return Id + "," + Score + "," + RewardName;
    }
}

——GroupJoin: 将一个集合与另一个集合通过指定键分组

using System;
using System.Collections.Generic;
using System.Linq;

class MainClass
{
    static List<Person> personList = new List<Person>()
    {
        new Person(){ Id=1,Name="小明",Age=20,Score=100},
        new Person(){ Id=2,Name="小王",Age=40,Score=80},
        new Person(){ Id=3,Name="小刘",Age=60,Score=60},
    };
    static List<Reward> rewardList = new List<Reward>()
    {
        new Reward(){ Id=1,Score=101,RewardName="奖励1"},
        new Reward(){ Id=2,Score=80,RewardName="奖励2"},
        new Reward(){ Id=3,Score=60,RewardName="奖励3"},
    };

    static void Main(string[] args)
    {
        var list = personList.GroupJoin(rewardList, p => p.Score, r => r.Score, (p, result) => new { pList = p, count = result.Count() });

        foreach (var temp in list)
        {
            Console.WriteLine(temp);
        }
    }
}

class Person
{
    public int Id;
    public string Name;
    public int Age;
    public int Score;

    public override string ToString()
    {
        return Id + "," + Name + "," + Age + "," + Score;
    }
}

class Reward
{
    public int Id;
    public int Score;
    public string RewardName;

    public override string ToString()
    {
        return Id + "," + RewardName;
    }
}

——OrderBy:对集合排序,默认是从小到大排序

using System;
using System.Collections.Generic;
using System.Linq;

class MainClass
{
    static List<Person> personList = new List<Person>()
    {
        new Person(){ Id=1,Name="小明",Age=20,Score=100},
        new Person(){ Id=2,Name="小王",Age=60,Score=60},
        new Person(){ Id=3,Name="小刘",Age=60,Score=80},
    };

    static void Main(string[] args)
    {
        var list = personList.OrderBy((p) => p.Age).ThenBy((p) => p.Score);

        foreach (var temp in list)
        {
            Console.WriteLine(temp);
        }
    }
}

class Person
{
    public int Id;
    public string Name;
    public int Age;
    public int Score;

    public override string ToString()
    {
        return Id + "," + Name + "," + Age + "," + Score;
    }
}

——Reverse:反转集合中元素的顺序

using System;
using System.Collections.Generic;
using System.Linq;

class MainClass
{
    static List<Person> personList = new List<Person>()
    {
        new Person(){ Id=1,Name="小明",Age=20,Score=100},
        new Person(){ Id=2,Name="小王",Age=40,Score=80},
        new Person(){ Id=3,Name="小刘",Age=60,Score=60},
        new Person(){ Id=3,Name="小刘",Age=60,Score=60},
    };

    static void Main(string[] args)
    {
        var list = personList.AsEnumerable().Reverse();

        foreach (var temp in list)
        {
            Console.WriteLine(temp);
        }
    }
}

——GroupBy:自身分组查询

using System;
using System.Collections.Generic;
using System.Linq;

class MainClass
{
    static List<Person> personList = new List<Person>()
    {
        new Person(){ Id=1,Name="小明",Age=20,Score=100},
        new Person(){ Id=2,Name="小王",Age=40,Score=80},
        new Person(){ Id=3,Name="小刘",Age=60,Score=60},
        new Person(){ Id=4,Name="小赵",Age=30,Score=60},
    };

    static void Main(string[] args)
    {
        var list = personList.GroupBy((p) => p.Score, (score, p) => new { score = score, count = p.Count() });

        foreach (var temp in list)
        {
            Console.WriteLine(temp);
        }
    }
}

class Person
{
    public int Id;
    public string Name;
    public int Age;
    public int Score;

    public override string ToString()
    {
        return Id + "," + Name + "," + Age + "," + Score;
    }
}

——Any和All:判断集合中是否满足某个/条件

using System;
using System.Collections.Generic;
using System.Linq;

class MainClass
{
    static List<Person> personList = new List<Person>()
    {
        new Person(){ Id=1,Name="小明",Age=20,Score=100},
        new Person(){ Id=2,Name="小王",Age=40,Score=80},
        new Person(){ Id=3,Name="小刘",Age=60,Score=60},
    };

    static void Main(string[] args)
    {
        bool b1 = personList.Any((p) => p.Age < 50);
        bool b2 = personList.All((p) => p.Age < 50);

        Console.WriteLine(b1);
        Console.WriteLine(b2);
    }
}

class Person
{
    public int Id;
    public string Name;
    public int Age;
    public int Score;

    public override string ToString()
    {
        return Id + "," + Name + "," + Age + "," + Score;
    }
}

——Skip:跳过指定个元素查询

using System;
using System.Collections.Generic;
using System.Linq;

class MainClass
{
    static List<Person> personList = new List<Person>()
    {
        new Person(){ Id=1,Name="小明",Age=20,Score=100},
        new Person(){ Id=2,Name="小王",Age=40,Score=80},
        new Person(){ Id=3,Name="小刘",Age=60,Score=60},
    };

    static void Main(string[] args)
    {
        var list = personList.Skip(1);

        foreach (var temp in list)
        {
            Console.WriteLine(temp);
        }
    }
}

class Person
{
    public int Id;
    public string Name;
    public int Age;
    public int Score;

    public override string ToString()
    {
        return Id + "," + Name + "," + Age + "," + Score;
    }
}

——Take:只查询指定个元素

using System;
using System.Collections.Generic;
using System.Linq;

class MainClass
{
    static List<Person> personList = new List<Person>()
    {
        new Person(){ Id=1,Name="小明",Age=20,Score=100},
        new Person(){ Id=2,Name="小王",Age=40,Score=80},
        new Person(){ Id=3,Name="小刘",Age=60,Score=60},
    };

    static void Main(string[] args)
    {
        var list = personList.Take(2);

        foreach (var temp in list)
        {
            Console.WriteLine(temp);
        }
    }
}

class Person
{
    public int Id;
    public string Name;
    public int Age;
    public int Score;

    public override string ToString()
    {
        return Id + "," + Name + "," + Age + "," + Score;
    }
}

——Sum、Average、Max、Min:计算集合中指定数字类型数据的总和、平均值、最大值、最小值

using System;
using System.Collections.Generic;
using System.Linq;

class MainClass
{
    static List<Person> personList = new List<Person>()
    {
        new Person(){ Id=1,Name="小明",Age=20,Score=100},
        new Person(){ Id=2,Name="小王",Age=40,Score=80},
        new Person(){ Id=3,Name="小刘",Age=60,Score=60},
    };

    static void Main(string[] args)
    {
        var sum = personList.Sum((p) => p.Age);
        var avg = personList.Average((p) => p.Age);
        var max = personList.Max((p) => p.Age);
        var min = personList.Min((p) => p.Age);

        Console.WriteLine(sum);
        Console.WriteLine(avg);
        Console.WriteLine(max);
        Console.WriteLine(min);
    }
}

class Person
{
    public int Id;
    public string Name;
    public int Age;
    public int Score;

    public override string ToString()
    {
        return Id + "," + Name + "," + Age + "," + Score;
    }
}

——Concat: 连接两个相同类型集合,合并为一个集合

using System;
using System.Collections.Generic;
using System.Linq;

class MainClass
{
    static List<int> numList1 = new List<int>() { 1, 2, 3 };
    static List<int> numList2= new List<int>() { 4, 5, 6 };

    static void Main(string[] args)
    {
        var list = numList1.Concat(numList2);

        foreach (var temp in list)
        {
            Console.WriteLine(temp);
        }
    }
}

——Distinct:从集合中去除掉重复的元素

using System;
using System.Collections.Generic;
using System.Linq;

class MainClass
{
    static List<int> numList = new List<int>() { 1, 2, 3, 1, 2, 3 };

    static void Main(string[] args)
    {
        var list = numList.Distinct();

        foreach (var temp in list)
        {
            Console.WriteLine(temp);
        }
    }
}

使用Distinct去重类中某个字段需要实现IEqualityComparer接口

using System;
using System.Collections.Generic;
using System.Linq;

class MainClass
{
    static List<Person> personList = new List<Person>()
    {
        new Person(){ Id=1,Name="小明",Age=20,Score=100},
        new Person(){ Id=2,Name="小王",Age=40,Score=80},
        new Person(){ Id=3,Name="小刘",Age=60,Score=60},
        new Person(){ Id=3,Name="小刘",Age=60,Score=60},
    };

    static void Main(string[] args)
    {
        var list = personList.Distinct(new Person());

        foreach (var temp in list)
        {
            Console.WriteLine(temp);
        }
    }
}

class Person : IEqualityComparer<Person>
{
    public int Id;
    public string Name;
    public int Age;
    public int Score;

    public new bool Equals(Person x, Person y)
    {
        if (x == null || y == null)
        {
            return false;
        }
        if (x.Age == y.Age)
        {
            return true;
        }
        return false;
    }

    public int GetHashCode(Person obj)
    {
        return obj.Age.GetHashCode();
    }

    public override string ToString()
    {
        return Id + "," + Name + "," + Age + "," + Score;
    }
}

——ElementAt:得到集合中指定索引的元素,与[]作用相同

using System;
using System.Collections.Generic;
using System.Linq;

class MainClass
{
    static List<int> numList = new List<int>() { 1, 2, 3};

    static void Main(string[] args)
    {
        var value = numList.ElementAt(2);

        Console.WriteLine(value);
    }
}

 ——Count:得到集合中满足指定条件的元素个数

using System;
using System.Collections.Generic;
using System.Linq;

class MainClass
{
    static List<int> numList1 = new List<int>() { 1, 2, 3 };

    static void Main(string[] args)
    {
        var count = numList1.Count((n) => n >= 2);

        Console.WriteLine(count);
    }
}

——First/Single和Last:得到集合中第一个/最后一个元素(如果集合中包含多个元素,使用Single会报错)

using System;
using System.Collections.Generic;
using System.Linq;

class MainClass
{
    static List<int> numList1 = new List<int>() { 1, 2, 3 };

    static void Main(string[] args)
    {
        var value1 = numList1.First((n) => n >= 2);
        var value2 = numList1.Last((n) => n < 3);

        Console.WriteLine(value1);
        Console.WriteLine(value2);
    }
}

——ToDictionary:将集合转换为字典 

using System;
using System.Collections.Generic;
using System.Linq;

class MainClass
{
    static List<Person> personList = new List<Person>()
    {
        new Person(){ Id=1,Name="小明",Age=20,Score=100},
        new Person(){ Id=2,Name="小王",Age=40,Score=80},
        new Person(){ Id=3,Name="小刘",Age=60,Score=60},
    };

    static void Main(string[] args)
    {
        var list = personList.ToDictionary(p => p.Id);

        foreach (var temp in list)
        {
            Console.WriteLine(temp);
        }
    }
}

class Person
{
    public int Id;
    public string Name;
    public int Age;
    public int Score;

    public override string ToString()
    {
        return Id + "," + Name + "," + Age + "," + Score;
    }
}

——ToList: 将集合转换为list

using System;
using System.Collections.Generic;
using System.Linq;

class MainClass
{
    static List<Person> personList = new List<Person>()
    {
        new Person(){ Id=1,Name="小明",Age=20,Score=100},
        new Person(){ Id=2,Name="小王",Age=40,Score=80},
        new Person(){ Id=3,Name="小刘",Age=60,Score=60},
    };

    static void Main(string[] args)
    {
        var dict = personList.ToDictionary(p => p.Id);
        List<Person> list = dict.Values.ToList();

        foreach (var temp in list)
        {
            Console.WriteLine(temp);
        }
    }
}

class Person
{
    public int Id;
    public string Name;
    public int Age;
    public int Score;

    public override string ToString()
    {
        return Id + "," + Name + "," + Age + "," + Score;
    }
}


——SequenceEqual:判断两个集合是否相等

using System;
using System.Collections.Generic;
using System.Linq;

class MainClass
{
    static void Main(string[] args)
    {
        List<int> list1 = new List<int>() { 1, 2, 3 };
        List<int> list2 = new List<int>() { 3, 1, 2 };
        list1 = list1.OrderBy(temp => temp).ToList();
        list2 = list2.OrderBy(temp => temp).ToList();

        Console.WriteLine(list1.SequenceEqual(list2));
    }
}

 文章来源地址https://www.toymoban.com/news/detail-405954.html

到了这里,关于C#中的LINQ的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • C#中var关键字详解:强类型、匿名类型和LINQ查询的妙用!

      在C#中, var 是强类型的,因为它在编译时会根据变量的初始化表达式推断出变量的实际类型,并且一旦确定了类型,就不能再更改。这种类型推断是在编译时进行的,因此代码中的变量在运行时是具有明确定义类型的。 下面是一个简单的示例,说明 var 的强类型特性

    2024年02月01日
    浏览(36)
  • C# Linq中的Select和SelectMany

    C#中Linq的select 语句很好理解,因为这个select类似于sql语句中的select——筛选出感兴趣的字段,但是SelectMany就不好理解了,本文主要讲解一下SelectMany,顺便和Select对比。   目录 1.SelectMany的官方定义  2.例子 3. Select和SelectMany的对比 4.SelectMany的扩展         官方定义很简单,

    2024年02月06日
    浏览(22)
  • linux中的“~”、“/”、“./”分别代表什么?

    1、“~” :表示主目录,也就是当前登录用户的用户目录。 表示返回到home目录 2、“/” :是指根目录:就是所有目录最顶层的目录,如下: 3、“./” :表示当前目录,./ 一般需要和其他文件夹或者文件结合使用,指代当前目录下的东西。 4、“. .” :表示上级目录  例如

    2024年02月05日
    浏览(57)
  • c# 从零到精通 数据库 定义LINQ查询表达式,从数组中查找长度小于7的所有项

    c# 从零到精通 数据库 定义LINQ查询表达式,从数组中查找长度小于7的所有项 using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LINQQuery { class Program { static void Main(string[] args) { //定义一个字符串数组 string[] strName = new string[] { “明日科技”,“C#编程词典”

    2024年02月10日
    浏览(39)
  • 代币中的decimal精度代表了什么

    精度的意义在于允许发送小数的代币。举例,一个CAT代币合约的精度为6。那么 你拥有1个CAT就意味着合约中的balance = 1 * 10^6 , 转账 0.1CAT出去的话,就需要输入 0.1*10^6 = 10^5。 也就时在涉及代币时,查询到的余额、转账的代币数量 都和 代币合约的精度挂钩 ERC20 合约默认的精度

    2024年02月02日
    浏览(38)
  • shell 脚本中的 '-f' 和 '-d' 分别代表什么意思

    shell脚本中,\\\'-f\\\' 和 \\\'-d\\\'是用于测试文件类型的条件表达式。 1、\\\'-f\\\'表达式: 表达式: \\\'[ -f file ]\\\' 描述: 判断给定路径是否是一个常规文件 (regular file)。 常规文件是指不是目录或设备文件的文件。 示例: if [ -f /path/to/file ]; then echo \\\"这是一个文件。\\\" fi 2、\\\'-d\\\'表达式: 表达式

    2024年02月04日
    浏览(48)
  • 以对象的方式访问html中的标签,比正则表达式更好用的方式获取html中的内容,linq方式直接获取所有的链接,更加先进的c#版本爬虫开源库

    这是我本人自己写的一个开源库,现已经发布到nuget,可以直接在vs的nuget包管理中搜索到,或者可以到nuget官网下载:https://www.nuget.org/packages/ZmjConvert/,也可以到我的个人网站上下载源码:https://www.zhaimaojun.cn/P/C%23%e6%a0%87%e7%ad%be%e7%b1%bb%e6%96%87%e6%9c%ac%e5%ba%8f%e5%88%97%e5%8c%96%e5%ba%9

    2024年03月15日
    浏览(46)
  • C# Linq 学会使用,学会自己编写Linq

    Linq我暂时理解为,一种内置的非常方便的数据查询的工具 我们先学习它的使用 //数据类 //新建了一个List数据,用来测试数据查询  //现在定义一个需求,需要查出 id2 的数据 引用Linq的命名空间  引用命名空间之后,我们的list对象,拥有了一个扩展方法,Where (扩展方法,在之前的博客

    2024年02月06日
    浏览(32)
  • C# Lambda,LINQ

    Lambda表达式和LINQ语句都是C#中用于查询和筛选数据的工具,但它们有一些异同点。 异同点: 1. 语法不同: Lambda表达式是一种匿名函数 ,它可以用于创建委托或表达式树。而LINQ语句是一种查询语句,它使用特定的和语法来查询数据。 2. 功能不同: Lambda表达式可以用于

    2024年02月09日
    浏览(309)
  • C# Linq 详解二

    目录 概述 七、OrderBy  八、OrderByDescending 九、Skip 十、Take 十一、Any 十二、All C# Linq 文档(一) 1.Where,2.Select,3.GroupBy,4.First / FirstOrDefault,5.Last / LastOrDefault C# Linq 文档(二) 1.OrderBy ,2.OrderByDescending,3.Skip,4.Take,5.Any,6.All C# Linq 文档(三) 1.Sum / Min / Max / Average,2.Dist

    2024年02月16日
    浏览(30)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包