Filter a list by another list C#

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


Try this:

List<ItemBO> items = ...;
ItemCategoryBO category = ...;

List<ItemBO> filteredItems = items
    .Where( i => i.ItemCategory.Equals(category) )
    .FirstOrDefault();

Updated to address OP's updated question:

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)

I think you actually should do this in two steps. First, get your distinct list of items. Then, from your items, get your list of categories. So:

// First, get the distinct list of items
List<ItemBO> items = new List<ItemBO>();
foreach ( var category in categories )
{
    foreach ( var item in category.Items )
    {
        if ( !items.Contains(item) )
            items.Add(item);
    }
}

// Second, get the list of items that have the category.
List<ItemBO> filteredItems = items
    .Where( i => i.ItemCategory.Equals(category) )
    .FirstOrDefault();

Tags:

C#

Linq