简体   繁体   English

LINQ子选择错误

[英]LINQ sub-select Error

I have object with this structure. 我对此结构有异议。

public class OrderItem
{
    public string idProduct { get; set; }
    public int quantity { get; set; }
    public List<WarehouseItem> WarehouseInfo = new List<WarehouseItem>();
}

public class WarehouseItem
{
    public string Name{ get; set; }
    public string LocnCode{ get; set; }
}

I need to get all LocnCode and make distinct by them so in result it should be List<string> . 我需要获取所有LocnCode并由它们区分,因此结果应为List<string> I am trying do this 我正在尝试这样做

List<string> codes = itemList.Select(x => x.WarehouseInfo.Select(y => y.LocnCode)).Distinct();

but have this Error: 但是有这个错误:

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<System.Collections.Generic.IEnumerable<string>>' to 'System.Collections.Generic.List<string>'.

How to do it? 怎么做?

You can use Enumerable.SelectMany to flatten the hierarchy: 您可以使用Enumerable.SelectMany展平层次结构:

List<string> distinctCodes = itemList
      .SelectMany(x => x.WarehouseInfo)
      .Select(y => y.LocnCode)
      .Distinct()
      .ToList();
List<string> codes = itemList.SelectMany(x => x.WarehouseInfo)
                             .Select(y => y.LocnCode)
                             .Distinct()
                             .ToList();

Or even change little bit from your code using SelectMany 甚至可以使用SelectMany从代码中进行一些更改

List<string> codes = itemList.SelectMany(x => x.WarehouseInfo
                                               .Select(y => y.LocnCode))
                             .Distinct()
                             .ToList();

Other version: 其他版本:

var query = from order in items
            from warehouse in order.WarehouseInfo 
            select warehouse.LocnCode ;

List<string> codes = query.Distinct().ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM