【问题标题】:SelectMany from grouped element从分组元素中选择多
【发布时间】:2016-07-10 09:50:28
【问题描述】:

在我下面的代码中,我想获得 Invoices 及其汇总的 InvoiceLine 总数,以及与每个 Invoice 关联的 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)

错误:

类型参数不能从用法中推断出来。尝试明确指定类型参数。

有什么想法吗?

提前致谢。

【问题讨论】:

标签: c# entity-framework linq linq-to-entities


【解决方案1】:

对象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

【讨论】:

  • 成功了!当我将鼠标悬停在Tracks 上时,我自己也得出了结论,上面写着IEnumerable&lt;char&gt;。谢谢!
猜你喜欢
  • 2017-04-20
  • 1970-01-01
  • 2021-12-28
  • 1970-01-01
  • 1970-01-01
  • 2016-09-22
  • 1970-01-01
  • 2016-07-02
  • 1970-01-01
相关资源
最近更新 更多