按另一个列表过滤列表 C# [英] Filter a list by another list C#

查看:29
本文介绍了按另一个列表过滤列表 C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下业务对象:

    public class ItemCategoryBO
    {
       public string ItemCategory { get; set; }
       public string Title { get; set; }
    }

    public class ItemBO
    {
       public int ItemId { get; set; }
       public string Title { get; set; }
       public string ItemCategory { get; set; } 
    }

    List<ItemCategoryBO> categoryList = new List<ItemCategoryBO>();

    ItemCategoryBO itemCategory = new ItemCategoryBO();
    itemCategory.ItemCategoryCd = "CARS";
    itemCategory.Title = "Cars";

    ItemCategoryBO itemCategory2 = new ItemCategoryBO();
    itemCategory.ItemCategoryCd = "PLANES";
    itemCategory.Title = "Planes";

    categoryList.Add(itemCategory);
    categoryList.Add(itemCategory2);

    List<ItemBO> itemList = new List<ItemBO>();

    ItemBO item1 = new ItemBO();
    item1.ItemId = 1;
    item1.Title = "1st item";
    item1.ItemCategoryCd = "OTHER";

    ItemBO item2 = new ItemBO();
    item2.ItemId = 2;
    item2.Title = "2nd Item";
    item2.ItemCategoryCd = "CARS";

    ItemBO item3 = new ItemBO();
    item3.ItemId = 3;
    item3.Title = "3rd Item";
    item3.ItemCategoryCd = "PLANES";

    itemList.Add(item1);
    itemList.Add(item2);
    itemList.Add(item3);

如果我有几个类别的列表,我如何在类别列表中找到包含一个类别的项目列表?(在我的示例中,我想取回第 2 项和第 3 项)

If I have a list of a few categories, how could I find a list of items that contain a category in the list of categories? (In my example, I want to get back items 2 and 3)

推荐答案

如果您遇到以下情况:

List<ItemBO> items;
List<ItemCategoryBO> categories;

并且您希望获得属于您的类别列表中的类别的所有项目,您可以使用:

and you wish to get all the items that have a category that is in your list of categories, you can use this:

IEnumerable<ItemBO> result = items.Where(item =>
    categories.Any(category => category.ItemCategory.equals(item.ItemCategory))); 

Any 运算符枚举源序列,如果任何元素满足谓词给出的测试,则返回 true.在这种情况下,如果类别列表包含 ItemCategoryBO,其中它的 ItemCategory 字符串与项目的 ItemCategory 字符串相同,则它返回 true.关于它的更多信息 MSDN

The Any operator enumerates the source sequence and returns true if any element satisfies the test given by the predicate. In this case, it returns true if the categories list contains an ItemCategoryBO where its ItemCategory string is the same as the item's ItemCategory string. More information about it on MSDN

这篇关于按另一个列表过滤列表 C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆