[英]How do I select all distinct strings in a list of lists of another type?
I'm still very new with LINQ. 我对LINQ还是很陌生。 I have the following "simplified" data structure:
我具有以下“简化的”数据结构:
List<List<Field>> myData = new List<List<Field>>();
Field
consists of two string members, Type
and Name
. Field
由两个字符串成员Type
和Name
。
My goal is to get a List<string>
containing all distinct Name
corresponding to a given Type
. 我的目标是获取一个
List<string>
其中包含与给定Type
对应的所有不同Name
。 My first approach is this: 我的第一种方法是:
var test = myData
.Where(a => a.FindAll(b => b.Type.Equals("testType"))
.Select(c => c.Name)
.Distinct());
Does somebody have a hint for me? 有人对我有提示吗? =)
=)
You just need to use SelectMany
to flatten your list of lists and then proceed as normal 您只需要使用
SelectMany
来展平列表列表,然后照常进行即可
var test = myData.SelectMany(x => x)
.Where(x => x.Type == "testType")
.Select(x => x.Name)
.Distinct()
.ToList();
Or in query syntax 或以查询语法
var test = (from subList in myData
from item in subList
where item.Type == "testType"
select item.Name).Distinct().ToList();
Another way to do it using query notation: 使用查询表示法的另一种方法:
var test= from list in myData
from e in list
where e.Type=="testType"
group e.Name by e.Name into g
select g.Key;
But is better go for one of the @juharr's solutions 但是最好选择@juharr的解决方案之一
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.