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

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

C#中LINQ的Select與SelectMany函數(shù)使用_C#教程

作者:斯內(nèi)科 ? 更新時(shí)間: 2022-10-08 編程語言

LINQ的Select與SelectMany函數(shù)使用

Select擴(kuò)展函數(shù)

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

返回結(jié)果:

  • System.Collections.Generic.IEnumerable`1 其元素是調(diào)用轉(zhuǎn)換函數(shù)的每個元素的結(jié)果 source。

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

SelectMany擴(kuò)展函數(shù)

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

返回結(jié)果:? ? ? ?

  • System.Collections.Generic.IEnumerable`1 其元素是一種一對多轉(zhuǎn)換函數(shù)對輸入序列中的每個元素調(diào)用的結(jié)果。

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

測試程序如下:

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", "風(fēng)晴雪,17,女", "百里屠蘇,20,男,BB" };
? ? ? ? ? ? //Select只是每個元素獨(dú)立投影到新表單,
? ? ? ? ? ? IEnumerable<string[]> selectCollection = collection.Select(person => person.Split(','));
? ? ? ? ? ? Console.WriteLine($"Select表達(dá)式的返回類型:{selectCollection.GetType()}");
? ? ? ? ? ? Console.WriteLine($"Select集合的元素個數(shù):{selectCollection.Count()}");
? ? ? ? ? ? int index = 0;
? ? ? ? ? ? selectCollection.ToList().ForEach(p =>
? ? ? ? ? ? {
? ? ? ? ? ? ? ? index++;
? ? ? ? ? ? ? ? Console.WriteLine($"第【{index}】個數(shù)組:其元素個數(shù):{ p.Length}");
? ? ? ? ? ? ? ? p.ToList().ForEach(s => Console.WriteLine(" ?" + s));
? ? ? ? ? ? });
? ? ? ? ? ? Console.WriteLine("下面測試SelectMany...");
? ? ? ? ? ? //投影后合并元素。相當(dāng)于將多個集合的每一個元素全部拼接,組成一個大的集合
? ? ? ? ? ? var selectMany = collection.SelectMany(person => person.Split(','));
? ? ? ? ? ? Console.WriteLine($"SelectMany表達(dá)式的返回類型:{selectMany.GetType()}");
? ? ? ? ? ? Console.WriteLine($"SelectMany集合的元素個數(shù):{selectMany.Count()}");
? ? ? ? ? ? selectMany.ToList().ForEach(p => Console.WriteLine(p));
? ? ? ? ? ? Console.ReadLine();
? ? ? ? }
? ? }
}

程序運(yùn)行結(jié)果截圖:?

SelectMany和Select的區(qū)別

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

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

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}
};

通常情況下要遍歷一個嵌套的數(shù)組,我們不得不采用二重循環(huán)(for或者foreach),不過現(xiàn)在我們可以借助SelectMany進(jìn)行簡化處理(把每個內(nèi)嵌的List取出,因?yàn)槊恳粋€List都是IEnumerable,合并成一個大的IEnumerable)。

簡化如下:

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

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

欄目分類
最近更新