gpt4 book ai didi

C#:从 IEnumerable> 获取不同的 T

转载 作者:太空宇宙 更新时间:2023-11-03 17:40:58 24 4
gpt4 key购买 nike

假设有一个对象IEnumerable<IEnumerable<T>> ,从该对象中获取不同 T 列表的最简洁方法是什么?

示例代码:

var listOfLists = new List<List<string>>();

listOfLists.Add(new string[] {"a", "b", "c", "c"}.ToList());
listOfLists.Add(new string[] {"a", "f", "g", "h"}.ToList());
listOfLists.Add(new string[] {"j", "k", "l"}.ToList());

List<string> distinctList = listOfLists.MagicCombinationOfEnumerableMethods();

Console.WriteLine(string.Join(", ", distinctList));

输出会是这样的:

a, b, c, f, g, h, j, k, l

最佳答案

你需要Enumerable.SelectMany

Projects each element of a sequence to an IEnumerable and flattens the resulting sequences into one sequence

List<string> distinctList = listOfLists.SelectMany(r => r).Distinct().ToList();

您还可以修改代码以在列表中添加元素,例如:

listOfLists.Add(new List<string> {"a", "b", "c", "c"});

而不是创建数组然后将其转换为列表。

关于C#:从 IEnumerable<IEnumerable<T>> 获取不同的 T,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22865921/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com