Michael Low
Michael Low

Reputation: 24506

How to rewrite this foreach looping using linq?

Supposing I have two classes, Customer and Order, where one Customer can have one-or-many Orders associated to it.

class Customer
{
  Order[] Orders;
}

class Order
{
  int OrderId;
}

If for any given Customer, I want to find all the associated OrderId's, is there an easy way to do that using linq ? Something that gives the same result as the following foreach solution:

List<int> allOrderIds = new List<int>();
foreach (Order thisOrder in thisCustomer)
{
   allOrderIds.Add(thisOrder.OrderId);
}

TIA.

Upvotes: 0

Views: 1538

Answers (3)

Dan
Dan

Reputation: 3756

Use the select method. You should also keep the Orders as a List if you want to do a lot of linq statements on them.

thisCustomer.Orders.ToList().Select(o => o.OrderId).ToList();

Upvotes: 0

RPM1984
RPM1984

Reputation: 73112

You can use an extension method that many people create:

public static void ForEach<T>(this IEnumerable<T> enumeration, Action<T> action)
{
    foreach(T item in enumeration)
    {
        action(item);
    }
}

And use it like this:

thisCustomer.Orders.ForEach(c => allOrderIds.Add(o.OrderId));

Upvotes: 1

mqp
mqp

Reputation: 71945

var allOrderIds = thisCustomer.Orders.Select(o => o.OrderId).ToList();

Upvotes: 8

Related Questions