c# - 如何过滤列表如果它包含特定的类数据?
问题描述
我需要在 c# 中过滤列表数据的帮助。我有 3 个名为Product.cs
,Storage.cs
和Inventory.cs
.
public class Storage{
string StorageId;
string Name;
}
public class Inventory{
string InventoryId;
string StorageId;
string ProductId;
}
我得到了填充List<Storage> mStorages
,List<Product> mProduct
和List<Inventory> mInventories
。
我很难打印mStorages
包含特定productId
内容的内容,只能从mInventories
.
所以,我尝试了这个:
List<Storage> mFilteredStorage;
for(int i=0;i<mStorages.Count;i++){
if(mStorages[i] contain (productId from inventories)){
mFilteredStorage.add(mstorages[i]);
}
所以我可以mFilteredStorage
从库存中得到包含特定产品的产品。(在库存中有很多产品ID)。
我该怎么做才能得到它filteredStorage
?我尝试使用list.contains()
,但它只返回 true,最后在mFilteredStorage
.
真的需要你们的帮助。提前致谢。
解决方案
您可以使用 LINQ 来实现您的目标。由于Storage
has no ProductId
,查询将匹配StorageId
。
var filteredStoragesQry =
from storage in mStorages
where inventories.Any(inventory => inventory.StorageId == storage.StorageId)
select storage;
mFilteredStorages = filteredStoragesQry.ToList();
此查询适用于 LINQ to 对象,但它也适用于实体框架,当您替换上下文中的相应对象mStorages
时inventories
。DbSet
推荐阅读
- javascript - 世博会“Cannot GET /”传递参数时
- javascript - Redux 更新对象状态
- angular - PrimeNG TabView - 基于 URL 打开选项卡
- python - 显示所有根节点、父节点和子节点(甚至是重复节点)的树图
- angular - 更改卡片颜色的指令
- javascript - 如果子组件中有相关数据,则仅在父组件中显示图标,但为了获得数据,我必须单击该图标
- nginx - 更新 Nginx 块来做两件不起作用的事情
- python - Bigquery api 使用 python Api
- laravel - 如何在 laravel 中过滤模型的关系?
- arrays - 在 Google 表格中,按名称而不是列号链接到列