实体框架- Linq筛选子列表对象属性



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

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

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

相关内容

  • 没有找到相关文章

最新更新