[英]How to get Distinct elements from a List of List in c#
I have a list of list, where the child list is list of string. 我有一个列表列表,其中子列表是字符串列表。 The result i am expecting is list of all distinct strings. 我期待的结果是所有不同字符串的列表。 For eg: 例如:
var listoflist = new List<List<string>> { new List<string> { "A", "B", "C" },
new List<string> { "A", "B", "D", "E" } };
For the above list i expecting the output as {"A","B","C","D","E"} 对于上面的列表,我希望输出为{“A”,“B”,“C”,“D”,“E”}
This is the solution that i found , but i dont feels its a efficient solution.Please provide your thougths on this. 这是我找到的解决方案,但我觉得它不是一个有效的解决方案。请提供你的想法。
var listoflist = new List<List<string>> { new List<string> { "A", "B", "C" },
new List<string> { "A", "B", "D", "E" } };
List<string> distinctList = new List<string>();
listoflist.ForEach(list =>
{
distinctList.AddRange(list);
});
distinctList = distinctList.Distinct().ToList();
You can use Enumerable.SelectMany
to flatten the lists: 您可以使用Enumerable.SelectMany
来展平列表:
var list = listoflist.SelectMany(x => x).Distinct();
If you want to materialize the query and get a List<string>
, add ToList()
. 如果要实现查询并获取List<string>
,请添加ToList()
。
Here, 这里,
[TestClass]
public class Class1
{
[TestMethod]
public void test()
{
var listoflist = new List<List<string>>
{
new List<string> {"A", "B", "C"},
new List<string> {"A", "B", "D", "E"}
};
var result = listoflist.SelectMany(l=>l).Distinct().ToList();
Assert.AreEqual(result.Count, 5);
}
}
Use SelectMany :- 使用SelectMany : -
var res = listoflist.SelectMany(x => x).Distinct();
SelectMany
will flatten the list from which on which you can apply the Distinct method. SelectMany
将展平您可以应用Distinct方法的列表。 It will return IEnumerable<string>
. 它将返回IEnumerable<string>
。 If you want List<string>
as output then simply apply a ToList
which will materialize the result:- 如果你想要List<string>
作为输出,那么只需应用一个ToList
,它将实现结果: -
List<string> distinctList = listoflist.SelectMany(x => x).Distinct().ToList();
listofList.SelectMany().Distinct()
I would use, 我会用的,
var distinctValues= listoflist[0].Concat(listoflist[1]).GroupBy(a=>a).Select(x => x.First());
Here, first
will select first record and groupBy
will group the same values 在这里, first
将选择第一个记录, groupBy
将分组相同的值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.