Linq按子列表对象属性过滤

时间:2013-01-12 01:26:13

标签: linq entity-framework linq-to-sql

我正在尝试将以下列表中所有产品类别为“绿色”的供应商退回,我确信它很简单,但我正在努力:

    public class Supplier
    {
        public int SupplierID { get; set; }
        public string Name { get; set; }
        public List<Product> Products { get; set; }
    }

    public class Product
    {
        public int ProductID { get; set; }
        public string Name { get; set; }
        public Category Category { get; set; }
    }

    public class Category
    {
        public int ID { get; set; }
        public string Name { get; set; }

        public Category(int ID, string Name)
        {
            this.ID = ID;
            this.Name = Name;
        }
    }

    public void FilterList()
    {
        //Get All Suppiers That Have Products In 'Green' Category
        List<Supplier> GreenSupplierList = FullSupplierList.Where(x => x.Products.SelectMany(y => y.Category.Name == "Green")).ToList();
    }

    public List<Supplier> FullSupplierList
    {
        get
        {

            //Create List Object To Be Filter
            List<Supplier> supplierList = new List<Supplier>();
            int productCount = 0;
            for (int i = 0; i < 10; i++)
            {
                Category category;
                if (i > 3)
                    category = new Category(i, "Red");
                else
                    category = new Category(i, "Green");

                Supplier s = new Supplier();
                s.SupplierID = 1;
                s.Name = "Supplier " + i.ToString();
                s.Products = new List<Product>();

                for (int j = 0; j < 10; j++)
                {
                    productCount += 1;

                    Product p = new Product();
                    p.ProductID = productCount;
                    p.Name = "Product " + productCount.ToString();
                    p.Category = category;
                    s.Products.Add(p);
                }
                supplierList.Add(s);
            }
            return supplierList;
        }
    }

FullSupplierList只是一个返回填充列表的简单方法,但是在FilterList方法中我正在尝试编写正确的linq语句。

1 个答案:

答案 0 :(得分:4)

FullSupplierList.Where(s => s.Products.Any(p => p.Category.Name == "Green"))
                .ToList();