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

查看:149
本文介绍了通过另一个列表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:

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



ANY运算枚举源序列,如果任何元素满足了谓词给出的试验返回true。在这种情况下,如果该类别列表包含ItemCategoryBO那里其ItemCategory串是相同的项目的ItemCategory字符串返回true。
关于它的更多信息, MSDN

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

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