根据内部属性展平集合

时间:2018-10-31 21:32:32

标签: c# linq

给出以下类结构:

int Id;
string[] Codes;

以及以下数据:

Foo { Id = 1, Codes = new[] { "01", "02" } }
Foo { Id = 2, Codes = new[] { "02", "03" } }
Foo { Id = 3, Codes = new[] { "04", "05" } }

我想以下面的结构结尾。

Code = "01", Id = 1
Code = "02", Id = 1
Code = "02", Id = 2
Code = "03", Id = 2
Code = "04", Id = 3
Code = "05", Id = 3

我有以下查询,但这是给我一个集合作为ID,而不是我所追求的扁平结构。

collection.GroupBy(f => f.Codes.SelectMany(c => c), f => f.Id,
      (code, id) => new { Code = code, Id = id })
   .ToArray()

我想念什么?

2 个答案:

答案 0 :(得分:4)

SelectMany可以将每个项目的多个元素作为单个列表返回

items
    .SelectMany(foo => foo.Codes.Select(code => new { Id = foo.Id, Code = code }));

答案 1 :(得分:3)

迭戈·托雷斯的答案是正确的;我只会补充说,此查询以理解形式特别简洁且可读:

var q = from foo in foos
        from code in foo.Codes
        select new { Code = code, foo.Id };