简体   繁体   中英

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.

You can try IEnumerable extension method Join

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

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();

try something like that

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

The Szymon's solution seems better than mine.

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM