Martin
Martin

Reputation: 24316

Using LINQ to find the latest item in a collection which in turn has a collection

I have a collection of products, each product has a collection of Warehouses and then inside the collection of warehouses there is a collection of locations.

I need to return all products which I am doing fine but I need to return the locationWithStock which is a member of the collection of locations inside the collection of warehouses.

I have this so far but it's wrong, because StockDate is not a member of Warehouse but of its collection. I need only the Latest (most recent date) of the StockDateS, hence I need to look inside each StockDate which there is 1 in each memeber Location and only return the latest.

        var items = from j in products
              let locationWithStock =
                            j.Warehouses.OrderByDescending
                         (a => a.StockDate).FirstOrDefault()
                        select new 
                        {
                            Name = j.Name,
                            Warehouse = locationWithStock.Name
                        }

Edit

I will try and explain a bit more. Here is the hierarchy:

Products.

Each product has multiple warehouses.

Each warehouse has multiple locations.

I need to return all products and each product must contain the location name.

What is the criteria to find the location when there are multiple warehouses and multiple locations?

I must search in each warehouse and in turn each location, and return OUT OF ALL OF THEM the latest location (ONLY 1) which I detect using the StockDate.

Upvotes: 0

Views: 169

Answers (1)

Sanjeevakumar Hiremath
Sanjeevakumar Hiremath

Reputation: 11273

Products
each product.Warehouses multiple warehouses
each Warehouse.Locations multiple locations in each Warehouse.

I assumed Whatever return all products which i am doing fine(in your question) translates to some condition on prodduct state, so I represented that condition with where p.Doing == "Fine" where clause in below code which you could modify appropriately.

var stocks =
           from p in products
           from w in p.Warehouses
           from l in w.locations
           group l by l.Date into g
           let maxDate = g.Max(l1 => l1.Date)
           select new { Product=p.Name, Location= g.Where(l2 => l2.Date == maxDate) };

Upvotes: 0

Related Questions