Question

Have this models:

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

I need to create foreach loop for distinct Employee.Id Thanks for the advice.

Was it helpful?

Solution

You can use SelectMany to flatten the lists and then get the Id with a Select

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

OTHER TIPS

Assume you have vmDeliveryList instance of your view model. With lambda syntax:

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

Unfortunately there is no Distinct() method in query syntax, so you can only select all ids, and then apply distinct:

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

var ids = allIds.Distinct();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top