c#Linq函數關鍵字大全-語法中文教程詳解-Chinar(簡化代碼利器)

Chinar blog www.chinar.xin

Linq 函數大全教程


本文提供全流程,中文翻譯

助力查詢學習 LinQ 查詢語句的具體用法、可用於備忘

爲初學者節省寶貴的時間,避免採坑!

Chinar —— 心分享、心創新!

我們的初衷是將一種簡單的生活方式帶給世人

使有限時間 具備無限可能

Chinar 教程效果:



全文高清圖片,點擊即可放大觀看 (很多人竟然不知道)


1. Where —— 篩選/過濾


Where —— 篩選滿足條件的數據

舉個例子

找 重量大於 30的狗

List<Dog> dogs = new List<Dog>()
{
    new Dog("金毛",  2000, 62),
    new Dog("二哈",  1500, 45),
    new Dog("泰迪",  1000, 15),
    new Dog("吉娃娃", 500,  10)
};

//1-查詢 狗狗中 重量大於30
dogs.Where(dog => dog.Weight > 30).ToList().ForEach(dog => print(dog.ToString()));

打印輸出:

Name: 金毛, Price: 2000, Weight: 62
Name: 二哈, Price: 1500, Weight: 45

Name: 金毛, Price: 2000, Weight: 62
Name: 二哈, Price: 1500, Weight: 45

數據類 —— 爲了簡化代碼,將該類放於 ChinarDemo.LinQ 命名空間中。便於以下例子使用此數據!

namespace ChinarDemo.LinQ
{
    /// <summary>
    /// 狗狗數據類
    /// </summary>
    public class Dog
    {
        public string Name;   //名稱
        public int    Price;  //價格
        public float  Weight; //重量


        /// <summary>
        /// 構造 —— 簡化代碼
        /// </summary>
        public Dog(string name, int price, float weight)
        {
            Name   = name;
            Price  = price;
            Weight = weight;
        }


        /// <summary>
        /// 便於打印輸出看效果 —— 簡化代碼
        /// </summary>
        public override string ToString()
        {
            return $"{nameof(Name)}: {Name}, {nameof(Price)}: {Price}, {nameof(Weight)}: {Weight}";
        }
    }
}

2. Select —— 返回選定類型


Select —— 從數據中返回指定的數據類型

舉個例子

1:從dogs序列中,返回狗的名字新序列
2:從dogs序列中,返回狗的價格新序列
3:從dogs序列中,返回狗的重量新序列

List<Dog> dogs = new List<Dog>()
{
    new Dog("金毛",  2000, 62),
    new Dog("二哈",  1500, 45),
    new Dog("泰迪",  1000, 15),
    new Dog("吉娃娃", 500,  10)
};


dogs.Select(_=>_.Name).ToList().ForEach(_=>Console.WriteLine(_));//( 狗的名字 )返回新的序列
dogs.Select(_=>_.Price).ToList().ForEach(_=>Console.WriteLine(_));//( 狗的價格 )返回新的序列
dogs.Select(_ => _.Weight).ToList().ForEach(_ => Console.WriteLine(_));//( 狗的重量 )返回新的序列

打印輸出:

金毛
二哈
泰迪
吉娃娃

2000
1500
1000
500

62
45
15
10

2.1 SelectMany —— 返回多個選定類型/協程排序


SelectMany —— 一個序列中每個元素的投影,合併爲一個序列,並返回。
在 UniRx 中多用於對協程執行順序進行管理

舉個例子

將狗狗的名字拆分爲字符類型,並返回
對3個協程依照需求順序執行

/// <summary>
/// 第一層
/// </summary>
public class One
{
    public string    Name;    //名字
    public int       Age;     //年齡
    public List<Two> TwoList; //兒子


    public One(string name, int age, List<Two> twoList)
    {
        Name    = name;
        Age     = age;
        TwoList = twoList;
    }
}


/// <summary>
/// 第二層
/// </summary>
public class Two
{
    public string      Name;      //名字
    public int         Age;       //年齡
    public List<Three> ThreeList; //兒子


    public Two(string name, int age, List<Three> threeList)
    {
        Name      = name;
        Age       = age;
        ThreeList = threeList;
    }


    public override string ToString()
    {
        return $"{nameof(Name)}: {Name}, {nameof(Age)}: {Age}, {nameof(ThreeList)}: {ThreeList}";
    }
}


/// <summary>
/// 第三層
/// </summary>
public class Three
{
    public int Age;   //年齡
    public int Score; //分數


    public Three(int age, int score)
    {
        Age   = age;
        Score = score;
    }


    public override string ToString()
    {
        return $"{nameof(Age)}: {Age}, {nameof(Score)}: {Score}";
    }
}


class Program
{
    static void Main(string[] args)
    {
        List<One> ones = new List<One> //第一層列表
        {
            new One("A1", 40, new List<Two> //第二層
            {
                new Two("A2_0", 20, new List<Three> {new Three(10, 100)}), //第三層
                new Two("A2_1", 20, new List<Three> {new Three(10, 100)}), //第三層
                new Two("A2_2", 20, new List<Three> {new Three(10, 100)})  //第三層
            }),
            new One("B1", 50, new List<Two>
            {
                new Two("B2", 30, new List<Three> {new Three(14, 70)})
            }),
            new One("C1", 70, new List<Two>
            {
                new Two("C2_0", 50, new List<Three> {new Three(25, 80)}),
                new Two("C2_1", 50, new List<Three> {new Three(25, 80)})
            }),
            new One("D1", 80, new List<Two>
            {
                new Two("D2", 60, new List<Three> {new Three(40, 50)})
            }),
        };
        #region 重載1

        IEnumerable<List<Two>> onesSelect     = ones.Select(_ => _.TwoList);     //Select 返回 List<Two>
        IEnumerable<Two>       onesSelectMany = ones.SelectMany(_ => _.TwoList); //第一個重載:返回 Two
        foreach (var v in onesSelect)
        {
            Console.WriteLine(v); //v=List<Two>
        }

        Console.WriteLine("----------------------------");
        foreach (var v in onesSelectMany)
        {
            Console.WriteLine(v); //v=Two
        }

        #endregion
        #region 重載 二

        Console.WriteLine("----------重載 二 ------------");
        //var onesSelectMany2 = ones.SelectMany((a, b) =>
        //    a.TwoList.Select(_ =>
        //    {
        //        _.Name = b + "---" + _.Name;
        //        return _;
        //    }));

        //這裏的 index 指的是 List<One> ones 中對象的索引
        IEnumerable<string> onesSelectMany2 = ones.SelectMany((one, index) => one.TwoList.Select(_ => "索引:" + index + "--名字:" + _.Name));
        foreach (var v in onesSelectMany2)
        {
            Console.WriteLine(v); //v=String
        }

        #endregion
        Console.ReadLine();
    }

打印輸出:

在這裏插入圖片描述


3. First —— 首次/第一個數據


First —— 返回數據中的第一項數據

舉個例子

取數組中滿足條件的 第一項 元素

int[] numbers  = {1, 2, 3, 4, 5, 6};        //數組
var   numFirst = numbers.First(i => i > 3); //返回滿足條件的第一個數據元素
print(numFirst);                            //輸出 4

打印輸出:

4

4. Distinct —— 找不同


Distinct —— 不同的元素通過,相同元素被剔除

舉個例子

//一個數據列表,並添加數據
List<int> ints = new List<int>()
{
    1, 2, 2, 2, 3, 2, 3, 4, 5, 6, 7, 8, 9, 10
};
ints.Distinct().ToList().ForEach(_ => print(_)); //遍歷輸出,剔除後的列表

打印輸出:相同元素被剔除,返回不同的

12345678910

5. Last —— 找不同


Last —— 最後一個元素

舉個例子

找到狗狗中的最後一個/滿足條件的最後一個

List<Dog> dogs = new List<Dog>()
{
    new Dog("金毛",  2000, 62),
    new Dog("二哈",  1500, 45),
    new Dog("泰迪",  1000, 15),
    new Dog("吉娃娃", 500,  10)
};

Dog dog = dogs.Last();                     //最後一個
print(dog.ToString());                     //:吉娃娃
Dog dog1 = dogs.Last(_ => _.Price > 1000); //傳入條件:價格在 1000以上 的狗中的最後一個。這裏由於數組是2000先加入,1500後加入。所以1500在後,返回的是1500。而並非2000
print(dog1.ToString());                    //:二哈

打印輸出:

Name: 吉娃娃, Price: 500, Weight: 10

Name: 二哈, Price: 1500, Weight: 45

6. Union —— 並集


  • Union —— 取2個集合的並集
  • 其實就是 2個序列中,剔除所有重複元素,取唯一值合併爲一個序列

舉個例子

剔除所有重複元素,取唯一,合併序列

int[]  chinarArray1 = new int[] {1, 2, 3, 4, 5};
int[]  chinarArray2 = new int[] {1, 4, 8, 6, 3, 2};
var    unionList    = chinarArray1.Union(chinarArray2).ToList();
string resultStr    = "";
unionList.ForEach(_ => resultStr = resultStr + _.ToString());
print(resultStr);

打印輸出:

1234586

7. (Min/Max/Count/Sum) —— 最小/最大/數量/求和


  • Min ——序列中 最小值
  • Max ——序列中 最大值
  • Count ——序列元素的 數量
  • Sum ——序列中元素 求和

舉個例子

數組中元素求和,取最大/最小值/元素數量

int[] ints  = new[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
var   min   = ints.Min();
var   max   = ints.Max();
var   count = ints.Count();
var   sum   = ints.Sum();
Console.WriteLine(min);   //0
Console.WriteLine(max);   //9
Console.WriteLine(count); //10
Console.WriteLine(sum);   //45

打印輸出:

0
9
10
45

8. OrderBy/Descending —— 升序/降序


  • OrderBy —— 按照給定條件對序列元素升序排序
  • OrderByDescending —— 按照給定條件對序列元素降序排序

舉個例子

將一個散亂的數組,升序,降序 排列

int[] ints       = {5, 2, 8, 6, 4, 0, 3, 7, 9, 1};          //數字排序很亂的數組
var   ascending  = ints.OrderBy(_ => _).ToList();           //升序
var   descending = ints.OrderByDescending(_ => _).ToList(); //降序
ascending.ForEach(Console.Write);                           //0123456789
Console.WriteLine();                                        //換行
descending.ForEach(Console.Write);                          //9876543210
Console.ReadKey();

打印輸出:

0123456789
9876543210

9. Skip/Take —— 跳過、取定範圍


基礎都是依照 序列順序 依次執行

  • Skip —— 跳過指定數量元素,取剩餘元素
  • SkipWhile —— 根據(條件)跳過指定數量元素,取剩餘元素
  • Take —— 只取指定數量元素,跳過剩餘元素
  • TakeWhile —— 根據(條件)只取指定數量元素,跳過剩餘元素

takeWhile0 坑點:

  • 這裏第一項就小於5,條件不滿足返回 false
  • 後邊的元素就不再進行比較了,比較結束
  • 所以沒有取到任何元素,跳過了剩餘所有元素。
  • Count 爲 0

SkipWhileTakeWhile
二者都是在條件爲 false 時,結束比較

舉個例子

skip 跳過前10項,取剩餘元素
skipWhile 跳過小於 5 元素,取剩餘元素
take 只取前10項,跳過剩餘元素
takeWhile 只取小於 5 元素,跳過剩餘元素

int[] ints      = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19};
var   skip      = ints.Skip(10).ToList();              //跳過前 10 項元素,取剩餘元素
var   skipWhile = ints.SkipWhile(_ => _ < 5).ToList(); //跳過小於 5 元素,取剩餘元素
var   take      = ints.Take(10).ToList();              //只取前 10 項元素,跳過剩餘元素
var   takeWhile = ints.TakeWhile(_ => _ < 5).ToList(); //只取小於 5 元素,跳過剩餘元素
skip.ForEach(_ => Console.Write(_ + "-"));             //10-11-12-13-14-15-16-17-18-19-
Console.WriteLine();                                   //
skipWhile.ForEach(_ => Console.Write(_ + "-"));        //5-6-7-8-9-10-11-12-13-14-15-16-17-18-19-
Console.WriteLine();                                   //
take.ForEach(_ => Console.Write(_ + "-"));             //0-1-2-3-4-5-6-7-8-9-
Console.WriteLine();                                   //
takeWhile.ForEach(_ => Console.Write(_ + "-"));        //0-1-2-3-4-
Console.WriteLine();                                   //

var takeWhile0 = ints.TakeWhile(_ => _ > 5).ToList();//跳過了所有元素,取不到任何元素
Console.WriteLine("takeWhile0 數量爲:" + takeWhile0.Count);// 0
Console.ReadKey();

打印輸出:

10-11-12-13-14-15-16-17-18-19-
5-6-7-8-9-10-11-12-13-14-15-16-17-18-19-
0-1-2-3-4-5-6-7-8-9-
0-1-2-3-4-
takeWhile0 數量爲:0

10. OfType —— 類型篩選


  • OfType —— 根據指定類型,篩選對象

舉個例子

從一個 Object[]數組中,找出指定類型元素

  • 找出類型爲 Int 的元素
  • 找出類型爲 String 的元素
object[] objects    = {1, 2, 3, 4, 5, "字符1", "字符2", "字符3"};
var      intList    = objects.OfType<int>().ToList();    //找出類型爲 Int 的元素
var      stringList = objects.OfType<string>().ToList(); //找出 String 元素
intList.ForEach(_ => Console.Write(_ + "-"));    //1-2-3-4-5-
Console.WriteLine();
stringList.ForEach(_ => Console.Write(_ + "-")); //字符1-字符2-字符3-
Console.ReadKey();

打印輸出:

1-2-3-4-5-
字符1-字符2-字符3-

11. Intersect —— 交集


  • Intersect —— 取兩個序列的交集,也就是兩個序列的相同元素

舉個例子

兩個數組序列中,找出相同元素,生成兩個序列的交集

  • 135
  • 張三、李四
int[]            ints1         = {1, 2, 3, 4, 5};
int[]            ints2         = {1, 3, 5, 7, 9};
IEnumerable<int> intersectInts = ints1.Intersect(ints2);
//135 爲兩個數組相同元素,被返回
intersectInts.ToList().ForEach(Console.Write);
Console.WriteLine();


string[]            strs1            = {"張三", "李四"};
string[]            strs2            = {"張三", "李四", "王五", "幹啥呢?"};
IEnumerable<string> intersectIntStrs = strs1.Intersect(strs2);
//張三、李四 
intersectIntStrs.ToList().ForEach(Console.Write);
Console.ReadKey();

打印輸出:

135
張三李四

12. Except —— 差集


  • Except —— 取兩個序列的差集,求出A、B中彼此沒有的元素

Except 坑點:

  • 序列A/B取差集,順序不同,返回結果不同
  • 也就是A except B,與B except A是不同d

要點就是:
A序列取B序列 —— 返回A有,B沒有的值
B序列取A序列 —— 返回B有,A沒有的值

如此簡單

舉個例子

將2個整數序列,1和2數組分別求差集

  • 相互調換位置,看結果
int[] ints1    = {1, 2, 3, 4, 5}; //獨有的爲:2、4
int[] ints2    = {1, 3, 5, 7, 9}; //獨有的爲:7、9
var   except12 = ints1.Except(ints2);
except12.ToList().ForEach(Console.Write); //24
Console.WriteLine();
Console.WriteLine("以下爲 2 取 1");
var except21 = ints2.Except(ints1);
except21.ToList().ForEach(Console.Write); //79
Console.ReadKey();

打印輸出:

24
以下爲 21
79

支持

May Be —— 開發者,總有一天要做的事!


擁有自己的服務器,無需再找攻略

Chinar 提供一站式《零》基礎教程

使有限時間 具備無限可能!

Chinar 知你所想,予你所求!( Chinar Blog )


Chinar

END

本博客爲非營利性個人原創,除部分有明確署名的作品外,所刊登的所有作品的著作權均爲本人所擁有,本人保留所有法定權利。違者必究

對於需要複製、轉載、鏈接和傳播博客文章或內容的,請及時和本博主進行聯繫,留言,Email: [email protected]

對於經本博主明確授權和許可使用文章及內容的,使用時請註明文章或內容出處並註明網址

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章