Search code examples
c#linq

Filter a list by another list C#


I have the following business objects:

    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);

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)


Solution

  • If you have a situation like:

    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))); 
    

    The Any() operator enumerates the source sequence and returns true as soon as an item 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