我有类似的物品清单:
Item item = new Item {ID = 1, Name = 'One'};
Item item2 = new Item {ID = 2, Name = 'Two'};
List<Item> items = new List<Item>;
items.Add(item);
items.Add(item2);
然后我还有其他项目的另一个列表,其中的一个列表是与第一个项目列表的关联的列表:
OtherItem otherItem = new OtherItem {ID = 1, Name = 'OtherOne', ListOfItems = {1,2}};
OtherItem otherItem2 = new OtherItem {ID = 2, Name = 'OtherTwo', , ListOfItems = {2}};
List<OtherItem> otherItems = new List<OtherItem>;
otherItems.Add(otherItem);
otherItems.Add(otherItem2);
现在,我想返回OtherItem ListOfItems中包含的Item列表。出于示例的原因,我如何返回在OtherItem的ListOfItems包含ID:1的Item列表?
答案 0 :(得分:1)
items.Where(i => otherItems.Any(oi => oi.ListOfItems.Any(li => li == i.ID)))
答案 1 :(得分:1)
您可以使用Where
:
List<OtherItem> otherItems = new List<OtherItem>
{
new OtherItem { ID = 1, Name = "OtherOne", ListOfItems = { 1, 2 } },
new OtherItem { ID = 2, Name = "OtherTwo", ListOfItems = { 2 } }
};
var ID = 1;
var result = otherItems.Where(s => s.ListOfItems.Any(x => x == ID))
.Select(s => new { s.ID, s.Name });