嵌套列表中的不同项

时间:2014-06-04 12:08:02

标签: c# list distinct-values

有这个型号:

public class VMDeliveryList  //[View-model]
{
    public List<ContractDelivery> ContractDeliveryList { get; set; }
}

public class ContractDelivery
{
    public Contract Contract { get; set; }
    public List<Delivery> DeliveryList { get; set; }
}

public class Delivery
{
    public int Id { get; set; }
    public Employee Employee { get; set; }
}

public class Employee
{
    public int Id { get; set; }
}

我需要为不同的Employee.Id创建foreach循环 谢谢你的建议。

2 个答案:

答案 0 :(得分:3)

您可以使用SelectMany展平列表,然后使用Id

获取Select
foreach(int id in viewModel.ContractDeliveryList.SelectMany(a => a.DeliveryList)
                                                .Select(b => b.Employee.Id)
                                                .Distinct() )
{
    ....
}

答案 1 :(得分:1)

假设您拥有视图模型的vmDeliveryList实例。使用lambda语法:

var ids = vmDeliveryList.ContractDeliveryList
                        .SelectMany(cdl => cdl.DeliveryList)
                        .Select(dl => dl.Employee.Id)
                        .Distinct();

不幸的是,查询语法中没有Distinct()方法,因此您只能选择所有ID,然后应用distinct:

var allIds = from cdl in vmDeliveryList.ContractDeliveryList
             from dl in cdl.DeliverList
             select dl.Employee.Id;

var ids = allIds.Distinct();