如何使用Linq在c#中过滤嵌套的ICollection列表

时间:2017-03-30 09:01:43

标签: c# linq

考虑以下类结构:

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

    }
}

经过测试:

  • Visual Studio 2017社区版
  • 控制台应用(.NET Framework)模板

问题:

  • 如何在'getItemSet'函数中获取具有指定'Type'属性的所有Item的结果ItemSet?
  • 'getItemSet'不会编译,因为“where”提供IEnumerable但我需要ICollection。

1 个答案:

答案 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();