简体   繁体   English

如何在其他类型的列表中选择所有不同的字符串?

[英]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由两个字符串成员TypeName

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.

相关问题 如何从多个列表中选择不同且有序的数据到通用列表中? - How can I select distinct and ordered data into a generic list from multiple lists? 如何通过包含列表中的所有列表来 Select 列表 - How to Select a list by having all the lists in that list 如何选择列表中的所有元素 <Int32> 进入另一个列表 <Int32> 与LINQ? - How do I select all elements in List<Int32> into another List<Int32> with LINQ? 如何从列表中选择在另一个列表/模型中没有相关对象的所有对象 - How do I select all objects from a list that have no related objects in another list/model LINQ:如何压缩2个列表并选择第一个列表不同的元素? - LINQ: how to zip 2 lists and select elements where first list is distinct? 如何选择另一个列表中包含的不同元素列表? - How to select a distinct list of elements contained in another list? 使用带有不同字符串列表的select语句分组 - Group by with a select statement with Distinct list of Strings 如何从另一种方法生成的列表中 select 和 object ? - How do I select an object from a list generated by another method? 如何使用MVC中的单选按钮列表选择类型? - How do I select a type by using a radiobutton list in MVC? LINQ选择列表中的所有其他类型列表中的项目 - LINQ select items in a list that are all in a list of another type
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM