2

我有这个结构的对象。

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

怎么做?

4

3 回答 3

4

您可以使用Enumerable.SelectMany扁平化层次结构:

List<string> distinctCodes = itemList
      .SelectMany(x => x.WarehouseInfo)
      .Select(y => y.LocnCode)
      .Distinct()
      .ToList();
于 2013-03-25T17:41:18.157 回答
1
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();
于 2013-03-25T17:39:57.677 回答
0

其他版本:

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

List<string> codes = query.Distinct().ToList();
于 2013-03-25T17:45:13.987 回答