从分组元素中选择多个

SelectMany from grouped element

在我下面的代码中,我想获得 Invoices 及其总计 InvoiceLine 以及与每个 Invoice.[=17 关联的 Tracks 的列表=]

var screenset =
  from invs in context.Invoices
  join lines in context.InvoiceLines on invs.InvoiceId equals lines.InvoiceId
  join tracks in context.Tracks on lines.TrackId equals tracks.TrackId
  group new { invs, lines, tracks }
  by new
  {
      invs.InvoiceId,
      invs.InvoiceDate,
      invs.CustomerId,
      invs.Customer.LastName,
      invs.Customer.FirstName
  } into grp
  select new
  {
      InvoiceId = grp.Key.InvoiceId,
      InvoiceDate = grp.Key.InvoiceDate,
      CustomerId = grp.Key.CustomerId,
      CustomerLastName = grp.Key.LastName,
      CustomerFirstName = grp.Key.FirstName,
      CustomerFullName = grp.Key.LastName + ", " + grp.Key.FirstName,
      TotalQty = grp.Sum(l => l.lines.Quantity),
      TotalPrice = grp.Sum(l => l.lines.UnitPrice),
      Tracks = grp.SelectMany(t => t.tracks)
  };

然而,在最后一行我做了一个 SelectMany 给我一个错误:

Tracks = grp.SelectMany(t => t.tracks)

错误:

The type arguments cannot be inferred from the usage. Try specifying the type arguments explicitly.

知道为什么吗?

提前致谢。

对象 tracks 是单个轨道而不是列表。如果需要使用SelectMany,使用需要select一个列表才能:

Projects each element of a sequence to an IEnumerable and flattens the resulting sequences into one sequence.

所以改成:

Tracks = grp.Select(t => t.tracks)

SelectMany 的真正用途是当您有一个列表的列表并且您想要将这些列表转换为一个列表时。示例:

List<List<int>> listOfLists = new List<List<int>>()
{
    new List<int>() { 0, 1, 2, 3, 4 },
    new List<int>() { 5, 6, 7, 8, 9 },
    new List<int>() { 10, 11, 12, 13, 14 }
};

List<int> selectManyResult = listOfLists.SelectMany(l => l).ToList();

foreach (var r in selectManyResult)
    Console.WriteLine(r);

输出:

0
1
2
3
4
5
6
7
8
9
10
11
12
13
14