考虑以下类结构:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
public class ItemSet
{
public Guid ID { get; set; }
public ICollection<Item> Items { get; set; }
}
public class Item
{
public Guid ID { get; set; }
public string Type { get; set; }
}
class Program
{
static void Main(string[] args)
{
getItemSet("B2");
}
static public ItemSet generateCompleteItemSet()
{
Item item1 = new Item();
item1.ID = new Guid();
item1.Type = "A1";
Item item2 = new Item();
item2.ID = new Guid();
item2.Type = "B2";
Item item3 = new Item();
item3.ID = new Guid();
item3.Type = "B2";
ICollection<Item> items = new List<Item>();
items.Add(item1);
items.Add(item2);
items.Add(item3);
ItemSet itemSet = new ItemSet();
itemSet.ID = new Guid();
itemSet.Items = items;
return itemSet;
}
static public void getItemSet(string type)
{
ItemSet completeItemSet = generateCompleteItemSet();
ItemSet filteredItemSet = completeItemSet;
filteredItemSet.Items = completeItemSet.Items.Where(item => item.Type == type);
}
}
}
经过测试:
问题:
答案 0 :(得分:1)
(编辑 - 将所有项目和过滤的项目添加为List<Item>
)
//test data
List<Item> itemsList = new List<Item>();
itemsList.Add(new Item() { ID = Guid.NewGuid(), Type = "a" });
itemsList.Add(new Item() { ID = Guid.NewGuid(), Type = "a" });
itemsList.Add(new Item() { ID = Guid.NewGuid(), Type = "b" });
itemsList.Add(new Item() { ID = Guid.NewGuid(), Type = "c" });
List<ItemSet> itemSetList = new List<ItemSet>();
itemSetList.Add(new ItemSet() { ID = Guid.NewGuid(), Items = itemsList });
//select all items
var allItems = itemSetList.SelectMany(i => i.Items).ToList();
//filter items by type
var filteredItems = itemSetList.SelectMany(i => i.Items.Where(x => x.Type == "a")).ToList();