NutsAndBolts
NutsAndBolts

Reputation: 429

Linq one list to select multiple items from another list

I have three classes as below:

public class Product
{
    int id { get; set; }
    int creationDate { get; set; }
}
public class ProductList
{
    List<Product> productsList;
}

And

public class SelectedId
{
    List<int> selectedIds;
}

Now I have 2 lists:

  1. selectedIds

  2. products

    I want to get each Product from productsList whose Id is equal to the values in selectedId in the sequence of Ids mentioned in selectedIds.

Presently I am doing something like this:

foreach (var sID in selectedId)
{
   var product = productsList.First(x => x.id == sID);
   products.Add(product);
}

Please suggest a better way to do the same.

Upvotes: 1

Views: 4873

Answers (5)

Peter B
Peter B

Reputation: 24222

You can use .Where() and .Contains(), as follows:

var newList = productsList.Where(p => selectedIds.Contains(p.id)).ToList();

In plain text this means "get all items from productsList for which the id occurs in selectedIds".

Note - if there are duplicate values in selectedIds, these will be "distincted" away because we only return each Product at most once. If there are duplicates and you do care about also having duplicate Products as a result (+ in the same order as all the ids), then use a form such as this:

var newList = selectedIds.Select(id => productsList.First(p => p.id == id)).ToList();

Upvotes: 1

Ahmed Msaouri
Ahmed Msaouri

Reputation: 316

Can try a linq query with joint:


    var query = from id in selectedId
                       join product in productsList on id.selectedIds equals product.id
                       select new { id  = id.id , creationDate  = product.creationDate  };

Upvotes: 0

tmaj
tmaj

Reputation: 35075

There are many ways to achieve this, here's one:

var selected = productsList.Where(p => selectedIds.Contains(p.id))

You can use Any instead of Contains.

If you are adding selected to another collection of products you can use anotherCollection.AddRange.

Upvotes: 0

Tohm
Tohm

Reputation: 305

try something like that

var productsList =productsList.Where((product) =>  selectedId.Any((id) => id == product.Id));

The Szymon's solution seems better than mine.

Upvotes: 0

Szymon Tomczyk
Szymon Tomczyk

Reputation: 1319

You can try IEnumerable extension method Join

var result = products.Join(selectedIds, p => p.id, i => i, (p, i) => p).ToList()

Upvotes: 3

Related Questions