user1882453
user1882453

Reputation: 85

Linq Filter By Sub List Object Property

I am trying to return all suppliers who's product categories are "Green" in the following list, I'm sure its simple but am struggling:

    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 is just a simple method to return a populated list to work with or this example, but in the FilterList method is where I am trying to write the correct linq statement.

Upvotes: 1

Views: 3922

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236268

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

Upvotes: 4

Related Questions