以下のビジネス オブジェクトがあります。
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 を取得したいです)
ベストアンサー1
次のような状況の場合:
List<ItemBO> items;
List<ItemCategoryBO> categories;
カテゴリのリストにあるカテゴリのすべてのアイテムを取得したい場合は、次のようにします。
IEnumerable<ItemBO> result = items.Where(item =>
categories.Any(category => category.ItemCategory.equals(item.ItemCategory)));
このAny()
演算子はソースシーケンスを列挙し、述語で指定されたテストにアイテムが適合するとすぐに true を返します。この場合、カテゴリリストに ItemCategory 文字列がアイテムの ItemCategory 文字列と同じ ItemCategoryBO が含まれている場合に true を返します。詳細については、マイクロソフト