Embedd_0913
Embedd_0913

Reputation: 16565

Using LINQ query on Dictionary and List

I have a Dictionary<int, int> idsAndTypes = new Dictionary<int, int>(); and i have a

List<Product> products = new List<Product>() 

as list of products , the product class is as below

class Product
{
public int Id {get;set;}
public int Type{get;set;}

}

the dictionary idsAndTypes contains id's and types , now i want to use a linq query on the list to update the type of products based on id's in the dictionary.... i know the other way can be like following :

foreach (int item in idsAndTypes.Keys)
{
    Product.Where(product => product.Id == item).
      Select(product => product).ToList()[0].
      Type = idsAndTypes[item];
}

but i want to do it with a linq query to avoid the foreach loop, is there a way to do it ? Please suggest...

Upvotes: 0

Views: 1052

Answers (2)

G-Wiz
G-Wiz

Reputation: 7426

Your sample code is quite confusing. But I think what you want is:

products = products.Select(p => 
  { 
    p.LinkedProductType = idAndTypes[p.ID]; 
    return p;
  }
);

While this should achieve the goal, I would considered it an abuse of LINQ.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1503859

Well, LINQ is really for querying not for updating.

There may be a way of doing it without the loop, but I think the loop is the cleanest way. However, I wouldn't use that loop. You've got something which is very quick to look up, and you're just iterating through it... but then doing a lookup (effectively) on a slow data structure in terms of lookup. I'd do this:

foreach (Product p in products)
{
    int type;
    if (idsAndTypes.TryGetValue(product.Id, out type))
    {
        p.LinkedProductType = type;
    }
}

One difference here - that will update all the products in the list with values in the dictionary; your current code will only do the first product in the list with the given ID. I hope that isn't a problem.

Upvotes: 3

Related Questions