如何在另一类型列表的列表中选择所有不同的字符串

本文关键字:列表 字符串 选择 类型 | 更新日期: 2023-09-27 18:17:13

我对LINQ还是个新手。我有以下"简化"的数据结构:

List<List<Field>> myData = new List<List<Field>>();

Field由两个字符串成员TypeName组成。

我的目标是得到一个包含与给定Type对应的所有不同NameList<string>。我的第一个方法是:

var test = myData
  .Where(a => a.FindAll(b => b.Type.Equals("testType"))
  .Select(c => c.Name)
  .Distinct());
有谁能给我点提示吗?div =)

你只需要使用SelectMany来平坦你的列表列表,然后像往常一样进行

var test = myData.SelectMany(x => x)
    .Where(x => x.Type == "testType")
    .Select(x => x.Name)
    .Distinct()
    .ToList();

或在查询语法

var test = (from subList in myData
            from item in subList
            where item.Type == "testType"
            select item.Name).Distinct().ToList();

如何在另一类型列表的列表中选择所有不同的字符串

另一种使用查询符号的方法:

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;

但是最好选择@juharr的解决方案之一