整理一下 System.Linq.Enumerable 類中的那些比較少用的方法

来源:https://www.cnblogs.com/h82258652/archive/2018/04/10/8779461.html
-Advertisement-
Play Games

Linq 雖然用得多,但是裡面有一些方法比較少用,因此整理一下。Enumerable 類的所有方法可以在 MSDN 上查閱到:https://msdn.microsoft.com/zh-cn/library/system.linq.enumerable.aspx Aggregate 這個方法有三個重 ...


Linq 雖然用得多,但是裡面有一些方法比較少用,因此整理一下。Enumerable 類的所有方法可以在 MSDN 上查閱到:https://msdn.microsoft.com/zh-cn/library/system.linq.enumerable.aspx

 

Aggregate

這個方法有三個重載,先看第一個

Aggregate<TSource>(IEnumerable<TSource>, Func<TSource, TSource, TSource>)

參數是接受兩個 TSource 類型的輸入,返回一個 TSource 類型的輸出。

按照 MSDN 上的說明,輸入的第一個參數是累加的值,第二個參數是元素。

{
    int[] array = new[] { 1, 2, 3, 4, 5 };
    int result = array.Aggregate((sum, i) => sum + i);
    Console.WriteLine(result);
}
{
    string[] array = new string[] { "hello", "world", "!" };
    string result = array.Aggregate((combine, str) =>
    {
        return combine + " " + str;
    });
    Console.WriteLine(result);
}

則會輸出 15 和 hello world !

在第一次進入 Aggregate 的 Func 時,combine 的值為第一個元素的值,str 為第二個元素的值。

當輸入的序列的元素個數為 0 時,則拋出 InvalidOperationException 異常。

QQ截圖20180410123951

而當元素的個數只有一個的時候,則不會執行 Func。

接下來看第二個重載

Aggregate<TSource, TAccumulate>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate, TSource, TAccumulate>)

比起第一個重載,多了一個參數輸入參數 TAccumulate,泛型參數也變成了兩個。

{
    int[] array = new[] { 1, 2, 3, 4, 5 };
    long result = array.Aggregate(-1L, (sum, i) =>
    {
        return sum + i;
    });
    Console.WriteLine(result);
}

那麼這段代碼的輸出則會是 14。第一次進入 Func 的時候,sum 的值為 -1L,i 的值是 1,這個行為跟第一個重載稍微有點區別。

而且當元素只有一個的時候,也是會進入 Func 的

QQ截圖20180410124719

當序列為空的時候,也不會觸發到異常

QQ截圖20180410124856

直接等於輸入參數的值。

第三個重載

Aggregate<TSource, TAccumulate, TResult>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate, TSource, TAccumulate>, Func<TAccumulate, TResult>)

這個其實就是相當與第二個重載增加了最後一個參數

{
    string[] array = new string[] { "hello", "world", "!" };
    string result = array.Aggregate("start", (combine, str) =>
    {
        return combine + " " + str;
    }, end => end.ToUpperInvariant());
    Console.WriteLine(result);
}

執行後會輸出 START HELLO WORLD !。

最後的那個參數相對於對最終結果進行了一下處理,跟下麵的代碼是等價的。

{
    string[] array = new string[] { "hello", "world", "!" };
    string result = array.Aggregate("start", (combine, str) =>
    {
        return combine + " " + str;
    }).ToUpperInvariant();
    Console.WriteLine(result);
}

 

DefaultIfEmpty

第一個重載

DefaultIfEmpty<TSource>(IEnumerable<TSource>)

snipaste_20180410_130422

snipaste_20180410_130457

就是說,如果一個序列的元素個數是零個的話,那就返回一個只有一個 default(TSource) 元素的序列。感覺這沒啥用(lll¬ω¬)

看另一個重載

DefaultIfEmpty<TSource>(IEnumerable<TSource>, TSource)

多了個參數,猜也猜得出來了

snipaste_20180410_130857

snipaste_20180410_130942

唔,好像還是沒啥實用意義…………

 

Except

Except<TSource>(IEnumerable<TSource>, IEnumerable<TSource>)

求差集

snipaste_20180410_131437

A 序列減去 B 序列,並且去重了。

另一重載

Except<TSource>(IEnumerable<TSource>, IEnumerable<TSource>, IEqualityComparer<TSource>)

多了一個比較器

snipaste_20180410_131741

最後只會輸出 Hello,因為在 IgnoreCase 比較器下,world 和 WORLD 是一樣的。

 

GroupBy

雖然用得還是比較多,但是重載比較多,還是寫一下吧。

GroupBy<TSource, TKey>(IEnumerable<TSource>, Func<TSource, TKey>)

這個是最簡單的重載了。

snipaste_20180410_132350

根據 Age 分組,這個重載很簡單,也是最常用的。

GroupBy<TSource, TKey>(IEnumerable<TSource>, Func<TSource, TKey>, IEqualityComparer<TKey>)

多了一個比較器,不難

snipaste_20180410_132621

snipaste_20180410_132655

Key 會根據第一次匹配到的值。

GroupBy<TSource, TKey, TElement>(IEnumerable<TSource>, Func<TSource, TKey>, Func<TSource, TElement>)

snipaste_20180410_133013

第一個重載的改版而且,如果將上面的 person => person.Name 改為 person => person,那跟第一個重載沒區別。

GroupBy<TSource, TKey, TElement>(IEnumerable<TSource>, Func<TSource, TKey>, Func<TSource, TElement>, IEqualityComparer<TKey>)

多了一個比較器而已,不說了。

GroupBy<TSource, TKey, TResult>(IEnumerable<TSource>, Func<TSource, TKey>, Func<TKey, IEnumerable<TSource>, TResult>)

snipaste_20180410_133702

分完組後對每一組進行了一下處理。

GroupBy<TSource, TKey, TResult>(IEnumerable<TSource>, Func<TSource, TKey>, Func<TKey, IEnumerable<TSource>, TResult>, IEqualityComparer<TKey>)

比上面多了一個比較器,不說了。

GroupBy<TSource, TKey, TElement, TResult>(IEnumerable<TSource>, Func<TSource, TKey>, Func<TSource, TElement>, Func<TKey, IEnumerable<TElement>, TResult>)

多了元素選擇的參數重載,參考上面。

GroupBy<TSource, TKey, TElement, TResult>(IEnumerable<TSource>, Func<TSource, TKey>, Func<TSource, TElement>, Func<TKey, IEnumerable<TElement>, TResult>, IEqualityComparer<TKey>)

多了選擇器,不說。

 

Join

Join<TOuter, TInner, TKey, TResult>(IEnumerable<TOuter>, IEnumerable<TInner>, Func<TOuter, TKey>, Func<TInner, TKey>, Func<TOuter, TInner, TResult>)

這個其實不難,只要參考一下 SQL 中的 inner join 的話。

先初始化測試數據

List<Person> list1 = new List<Person>()
{
    new Person()
    {
        Id = 1,
        Gender = "M"
    },
    new Person()
    {
        Id = 2 ,
        Gender = "F"
    },
    new Person()
    {
        Id = 3,
        Gender = "M"
    }
};
List<Student> list2 = new List<Student>()
{
    new Student()
    {
        Id = 1,
        Name = "martin"
    },
    new Student()
    {
        Id = 2,
        Name = "valid void"
    },
    new Student()
    {
        Id = 4,
        Name = "justin"
    }
};

然後測試代碼走起

snipaste_20180410_135801

沒啥難的,等價於以下的 linq 寫法

snipaste_20180410_140346

Join<TOuter, TInner, TKey, TResult>(IEnumerable<TOuter>, IEnumerable<TInner>, Func<TOuter, TKey>, Func<TInner, TKey>, Func<TOuter, TInner, TResult>, IEqualityComparer<TKey>)

多了個比較器,用於比較 key,不說了。

 

GroupJoin

GroupJoin<TOuter, TInner, TKey, TResult>(IEnumerable<TOuter>, IEnumerable<TInner>, Func<TOuter, TKey>, Func<TInner, TKey>, Func<TOuter, IEnumerable<TInner>, TResult>)

看上去很複雜,但其實可以參考 Join 的輸入進行對比。

測試數據我們還是沿用 Join 的。執行測試代碼

snipaste_20180410_141037

對等的 linq 寫法如下

var result = (from person in list1
              join student in list2 on person.Id equals student.Id into studentGroup
              select new
              {
                  Id = person.Id,
                  Gender = person.Gender,
                  Students = studentGroup.ToList()
              }).ToList();

GroupJoin<TOuter, TInner, TKey, TResult>(IEnumerable<TOuter>, IEnumerable<TInner>, Func<TOuter, TKey>, Func<TInner, TKey>, Func<TOuter, IEnumerable<TInner>, TResult>, IEqualityComparer<TKey>)

多了一個比較器,不說了。

 

SelectMany

這個最近這段時間用得比較多,也記錄一下吧

SelectMany<TSource, TResult>(IEnumerable<TSource>, Func<TSource, IEnumerable<TResult>>)

測試代碼

snipaste_20180410_142134

簡單的來說就是將一個 IEnumerable<IEnumerable<T>> 的序列變成一個 IEnumerable<T> 的序列。

對等的 linq 寫法

snipaste_20180410_142358

感覺 linq 寫法會相對比較好理解的說。

SelectMany<TSource, TResult>(IEnumerable<TSource>, Func<TSource, Int32, IEnumerable<TResult>>)

Func 多了個 Int32 的參數,看測試代碼

snipaste_20180410_142808

snipaste_20180410_142818

很好理解,就是當前的索引。

SelectMany<TSource, TCollection, TResult>(IEnumerable<TSource>, Func<TSource, IEnumerable<TCollection>>, Func<TSource, TCollection, TResult>)

比起第一個就是多了個結果執行而已

snipaste_20180410_143405

會進入這個 Func 四次,前兩次是 helloword 那個 List,後兩次是 justin martin 那個 List。

SelectMany<TSource, TCollection, TResult>(IEnumerable<TSource>, Func<TSource, Int32, IEnumerable<TCollection>>, Func<TSource, TCollection, TResult>)

多了索引,參考上面。

 

SequenceEqual

序列比較,知道有這個東西,但平時好像沒有怎麼用過。

SequenceEqual<TSource>(IEnumerable<TSource>, IEnumerable<TSource>)

snipaste_20180410_144435

很好理解,首要前提肯定是元素個數相等,其次要每一個元素相等。

SequenceEqual<TSource>(IEnumerable<TSource>, IEnumerable<TSource>, IEqualityComparer<TSource>)

多了個比較器,不說了。

 

SkipWhile

Skip 倒是一直在用,SkipWhile 就用得比較少,也記錄一下吧。

SkipWhile<TSource>(IEnumerable<TSource>, Func<TSource, Boolean>)

不難,就是當 Func 返回 false 時停止。

snipaste_20180410_145113

因為當去到 3 的時候為 false,因此返回 3 和剩下的元素。

SkipWhile<TSource>(IEnumerable<TSource>, Func<TSource, Int32, Boolean>)

多了個索引而已,沒啥好說的。

 

ToDictionary

先看第一個重載

ToDictionary<TSource, TKey>(IEnumerable<TSource>, Func<TSource, TKey>)

不難,Func 就是獲取按照什麼來生成 Key。

snipaste_20180410_145804

另外使用這個方法是要註意,Key 是不能重覆的。

snipaste_20180410_145939

所以說實話,這方法平時比較少用。。。

ToDictionary<TSource, TKey>(IEnumerable<TSource>, Func<TSource, TKey>, IEqualityComparer<TKey>)

多了一個比較器,沒啥好說的。

ToDictionary<TSource, TKey, TElement>(IEnumerable<TSource>, Func<TSource, TKey>, Func<TSource, TElement>)

比起第一個重載,多了一個如何生成字典的值的 Func,也沒啥好說的。

ToDictionary<TSource, TKey, TElement>(IEnumerable<TSource>, Func<TSource, TKey>, Func<TSource, TElement>, IEqualityComparer<TKey>)

多了比較器,不說了。

 

ToLookup

這個有點像上面的 ToDictionary 的。

ToLookup<TSource, TKey>(IEnumerable<TSource>, Func<TSource, TKey>)

跟 ToDictionary 的第一個重載的輸入參數是一樣的。

snipaste_20180410_150636

ILookup<int, Person> 這個的結構類似於一個數組,然後每個數組的元素是一個 Group。

當元素的 Key 重覆的時候:

snipaste_20180410_151211

那麼這個 lookup 就只有一個 group 了,但這個 group 就會有多個元素。

ToLookup<TSource, TKey>(IEnumerable<TSource>, Func<TSource, TKey>, IEqualityComparer<TKey>)

ToLookup<TSource, TKey, TElement>(IEnumerable<TSource>, Func<TSource, TKey>, Func<TSource, TElement>)

ToLookup<TSource, TKey, TElement>(IEnumerable<TSource>, Func<TSource, TKey>, Func<TSource, TElement>, IEqualityComparer<TKey>)

這三個重載可以參考一下 ToDictionary 的重載,一樣的說。

 

Zip

這個方法就只有一個,沒別的重載

Zip<TFirst, TSecond, TResult>(IEnumerable<TFirst>, IEnumerable<TSecond>, Func<TFirst, TSecond, TResult>)

snipaste_20180410_151919

這裡就借用 MSDN 上的示例代碼了,看結果也看得出 Zip 這個操作的邏輯了。遍歷兩個序列進行操作,直到其中一個到達尾部。

 

另外像 TakeWhile 可以參考上面的 SkipWhile 就不說了。Distinct、Union 和 Intersect 平時也用得比較多,因此也不說了。


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 概述 UWP Community Toolkit Extensions 中有一個為TextBox 提供的 SurfaceDial 擴展 - SurfaceDialTextbox,本篇我們結合代碼詳細講解 SurfaceDialTextbox 的實現。 SurfaceDialTextbox 為 Tex ...
  • 《.NET 開源Protobuf-net從入門到精通》課程包含以下兩個部分: 一、.NET 開源Protobuf-net組件【數據存儲篇】 本次分享課程包含以下乾貨知識點: 1、什麼是Protobuffer? 2、Protobuffer應用場景介紹 3、為什麼Protocol Buffer性能這麼好 ...
  • net framework卸載 重裝 https://download.microsoft.com/download/E/4/1/E4173890-A24A-4936-9FC9-AF930FE3FA40/NDP461-KB3102436-x86-x64-AllOS-ENU.exe ...
  • 簡介 我們用C#來開發客戶端程式的時候,總會不可避免的需要調用外部程式或者訪問網站,本篇博客介紹了三種調用外部應用的方法,供參考 實現 第一種是利用shell32.dll,實現ShellExecute方法,該方法可同時打開本地程式、文件夾或者訪問網站,只要直接輸入路徑字元串即可, 如C:\Users ...
  • 為什麼要使用 ASP.NET Core? NET Core 剛發佈的時候根據介紹就有點心裡癢癢,微軟的尿性都懂的,新東西bug太多,現在2.0也發佈很久了,決定研究一下。 ASP.NET Core官方文檔https://docs.microsoft.com/en-us/aspnet/core/get ...
  • 1.連接SQLServer,創建資料庫TestDB; 2.添加EF引用,點擊工具-NuGet包管理器-管理解決方案的NuGet程式包, 搜索EntityFramework包,點擊安裝; 3.在Web.config中添加節點 其中Data Source為伺服器名,Initial Catalog為剛纔在 ...
  • 當年面試一家公司,面試官問我:一個int類型的數組怎麼獲取裡面第二大的數字? 給了我一張紙和一支筆讓我寫一個方法,我想了想便寫了一個方法: 然後問我能不能優化一下你的代碼,我當然回答可以了,尷尬的就是我想了半天也想不出來,當時腦子一片空白........; 最後無奈的說:可以優化,但是我現在想不到! ...
  • 需求: 最近項目里遇到了個問題,對方沒有提供直接獲取數據源的api介面,而是通過郵件發數據的。這就需要接收郵件後解析郵件內容獲得數據。 分析: 想在代碼里實時獲取郵件,可以通過郵件的幾個協議來實現,常用的幾個協議有POP3協議,SMTP協議,IAMP協議。 1. pop3:(Post Office ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...