关于c#:来自分组元素的SelectMany

SelectMany from grouped element

在我下面的代码中,我想得到Invoices及其合计InvoiceLine和每个Invoice关联的Tracks列表。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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)
  };

但是,在最后一行中,如果我做了选择,许多人会给我一个错误:

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

错误:

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

有什么想法吗?

事先谢谢。


对象tracks是单轨,不是列表。如果需要使用selectmany,请使用需要选择列表以:

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

所以把它改为:

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

selectmany的真正用法是当您有一个列表列表,并且希望将列表转换为单个列表时。例子:

1
2
3
4
5
6
7
8
9
10
11
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);

输出:

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