簡體   English   中英

LINQ子選擇錯誤

[英]LINQ sub-select Error

我對此結構有異議。

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; }
}

我需要獲取所有LocnCode並由它們區分,因此結果應為List<string> 我正在嘗試這樣做

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

但是有這個錯誤:

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

怎么做?

您可以使用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();

甚至可以使用SelectMany從代碼中進行一些更改

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

其他版本:

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