首页 > 解决方案 > 如何过滤列表如果它包含特定的类数据?

问题描述

我需要在 c# 中过滤列表数据的帮助。我有 3 个名为Product.cs,Storage.csInventory.cs.

public class Storage{
    string StorageId;
    string Name;
}

public class Inventory{
    string InventoryId;
    string StorageId; 
    string ProductId;
}

我得到了填充List<Storage> mStoragesList<Product> mProductList<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.

真的需要你们的帮助。提前致谢。

标签: c#generic-list

解决方案


您可以使用 LINQ 来实现您的目标。由于Storagehas no ProductId,查询将匹配StorageId

var filteredStoragesQry =
    from storage in mStorages
    where inventories.Any(inventory => inventory.StorageId == storage.StorageId)
    select storage;
mFilteredStorages = filteredStoragesQry.ToList();

此查询适用于 LINQ to 对象,但它也适用于实体框架,当您替换上下文中的相应对象mStoragesinventoriesDbSet


推荐阅读