在下面的代码中,我想获取Invoices及其总计InvoiceLine总数,以及与每个Tracks相关的Invoice列表。

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)


错误:


  不能从用法中推断出类型实参。尝试显式指定类型参数。


有什么想法吗?

提前致谢。

最佳答案

对象tracks是单个轨道,而不是列表。如果需要使用SelectMany,请使用需要选择一个列表以:


  将序列的每个元素投影到IEnumerable并展平
  产生的序列变成一个序列。


因此,将其更改为:

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

09-28 03:25