日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

C#中LINQ的Select與SelectMany函數使用_C#教程

作者:斯內科 ? 更新時間: 2022-10-08 編程語言

LINQ的Select與SelectMany函數使用

Select擴展函數

將序列中的每個元素投影到新表單。

返回結果:

  • System.Collections.Generic.IEnumerable`1 其元素是調用轉換函數的每個元素的結果 source。

Select只是每個元素獨立投影到新表單,每個元素獨自處理。

SelectMany擴展函數

一個序列的每個元素投影 System.Collections.Generic.IEnumerable`1 并將合并為一個序列將結果序列。

返回結果:? ? ? ?

  • System.Collections.Generic.IEnumerable`1 其元素是一種一對多轉換函數對輸入序列中的每個元素調用的結果。

SelectMany投影后合并元素。相當于將多個集合的每一個元素全部拼接,組成一個大的集合。

測試程序如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SelectManyDemo
{
? ? class Program
? ? {
? ? ? ? static void Main(string[] args)
? ? ? ? {
? ? ? ? ? ? string[] collection = new string[] { "張三,22,男", "李四,20,女,AA", "風晴雪,17,女", "百里屠蘇,20,男,BB" };
? ? ? ? ? ? //Select只是每個元素獨立投影到新表單,
? ? ? ? ? ? IEnumerable<string[]> selectCollection = collection.Select(person => person.Split(','));
? ? ? ? ? ? Console.WriteLine($"Select表達式的返回類型:{selectCollection.GetType()}");
? ? ? ? ? ? Console.WriteLine($"Select集合的元素個數:{selectCollection.Count()}");
? ? ? ? ? ? int index = 0;
? ? ? ? ? ? selectCollection.ToList().ForEach(p =>
? ? ? ? ? ? {
? ? ? ? ? ? ? ? index++;
? ? ? ? ? ? ? ? Console.WriteLine($"第【{index}】個數組:其元素個數:{ p.Length}");
? ? ? ? ? ? ? ? p.ToList().ForEach(s => Console.WriteLine(" ?" + s));
? ? ? ? ? ? });
? ? ? ? ? ? Console.WriteLine("下面測試SelectMany...");
? ? ? ? ? ? //投影后合并元素。相當于將多個集合的每一個元素全部拼接,組成一個大的集合
? ? ? ? ? ? var selectMany = collection.SelectMany(person => person.Split(','));
? ? ? ? ? ? Console.WriteLine($"SelectMany表達式的返回類型:{selectMany.GetType()}");
? ? ? ? ? ? Console.WriteLine($"SelectMany集合的元素個數:{selectMany.Count()}");
? ? ? ? ? ? selectMany.ToList().ForEach(p => Console.WriteLine(p));
? ? ? ? ? ? Console.ReadLine();
? ? ? ? }
? ? }
}

程序運行結果截圖:?

SelectMany和Select的區別

如果我們看這兩個擴展函數的定義很容易明白——Select是把要遍歷的集合IEnumerable逐一遍歷,每次返回一個T,合并之后直接返回一個IEnumerable,而SelectMany則把原有的集合IEnumerable每個元素遍歷一遍,每次返回一個IEnumerable,把這些IEnumerable的“T”合并之后整體返回一個IEnumerable。

因此我們可以說一般情況下SelectMany用于返回一個IEnumerable<IEnumerable>的“嵌套”返回情況(把每個IEnumerable合并后返回一個整體的IEnumerable)。因此在嵌套的時候往往可以節省代碼,例如輸出帶有以下的集合:

List<List<int>> numbers = new List<List<int>>()
{
? new List<int>{1,2,3},
? new List<int>{4,5,6},
? new List<int>{7,8,9}
};

通常情況下要遍歷一個嵌套的數組,我們不得不采用二重循環(for或者foreach),不過現在我們可以借助SelectMany進行簡化處理(把每個內嵌的List取出,因為每一個List都是IEnumerable,合并成一個大的IEnumerable)。

簡化如下:

var result = numbers.SelectMany(collection=>collection);
foreach(var item in result)
{
? ………………
}

原文鏈接:https://blog.csdn.net/ylq1045/article/details/105119193

欄目分類
最近更新