简体   繁体   English

Linq 一个列表到 select 另一个列表中的多个项目

[英]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:现在我有 2 个列表:

  1. selectedIds 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 .我想从productsList中获取每个Product ,其Id等于selectedIds中提到的Ids序列中selectedId中的值。

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可以试试 IEnumerable 扩展方法Join

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

You can use .Where() and .Contains() , as follows:您可以使用.Where().Contains() ,如下所示:

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 ".在纯文本中,这意味着“从productsList中获取其 id 出现在selectedIds中的所有项目”。

Note - if there are duplicate values in selectedIds , these will be "distincted" away because we only return each Product at most once.注意- 如果selectedIds中有重复的值,这些值将被“区分”掉,因为我们最多只返回每个 Product 一次。 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:如果有重复,并且您确实关心结果也会有重复的产品(+ 与所有 id 的顺序相同),则使用如下形式:

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. Szymon 的解决方案似乎比我的好。

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 .您可以使用Any而不是Contains

If you are adding selected to another collection of products you can use anotherCollection.AddRange .如果要将selected的产品添加到另一个产品集合中,则可以使用anotherCollection.AddRange

Can try a linq query with joint:可以尝试使用联合查询 linq :


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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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