[英]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 个列表:
selectedIds selectedIds
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 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.