【问题标题】:Subquery in Linq as a List unionLinq 中的子查询作为列表联合
【发布时间】:2018-10-24 07:03:52
【问题描述】:

假设你有Voyage 类,它有Tally 类。这个Tally 类有Shipment 类的集合。我正在尝试获取所有 Tallies 类的列表作为联合发货列表。
我已经对此进行了编码:

var shipments = booking.Voyages.Select(q => q.Tallies.Select(t => t.Loadings.Select(l=>l.Shipment))).ToList();

但问题是它以List<IEnumerable<IEnumerable<Shipment>>> 的形式返回结果,而我期望以IEnumerable<Shipment> 的形式返回结果。

这个问题有什么解决方案吗,或者我必须通过for 循环获取他们的发货。

【问题讨论】:

  • 如果要将列表转换为数组,请使用 .ToArray()
  • @Arphile - 不,我需要将结果作为列表

标签: c# linq collections


【解决方案1】:

您需要SelectMany 函数。 SelectMany 会将嵌套的 IEnumerable<IEnumerable<T>>; 展平为所有子级中的 IEnumerable<T>。因为你有多个层次,所以你需要多个SelectManys。

var shipments = booking.Voyages.SelectMany(
                  q => q.Tallies.SelectMany( 
                      t => t.Loadings.SelectMany(l=>l.Shipment)
                   )
                 ).ToList();

如果Shipment 属性是单个对象导航属性而不是集合,您将需要以下代码。

var shipments = booking.Voyages.SelectMany(
                  q => q.Tallies.SelectMany( 
                      t => t.Loadings.Select(l=>l.Shipment)
                   )
                 ).ToList();

【讨论】:

  • 发货是一流的。我的意思是总和是将 Shipment 实体作为集合收集并作为列表返回。
  • 返回错误('Headway.Domain.Models.Shipment' to 'long)
  • 答案已编辑。你想要嵌套的多选。或者,您可以另辟蹊径,从父 loading.booking 匹配的出货表中选择
  • 想象一下你有 Voyage 类,它有 Tally 类。这个 Tally 类有 Shipment 类的集合。我正在尝试获取 Loading 类中所有 Shipment 类的列表作为货物列表
  • 我看到了编辑过的答案,但它返回了这个错误(无法投射类型为 'WhereSelectListIterator2[Headway.Domain.Models.Voyage,System.Collections.Generic.IEnumerable1[System.Collections.Generic.List1[Headway.Domain.Models.Shipment]]]' to type 'System.Collections.Generic.List1[Headway.Domain.Models.Shipment ]'。)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多