1

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

    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 语句。

4

1 回答 1

4
FullSupplierList.Where(s => s.Products.Any(p => p.Category.Name == "Green"))
                .ToList();
于 2013-01-12T01:29:16.883 回答