简体   繁体   中英

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> . 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:

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

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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