Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Select from sub-list

Tags:

c#

.net

linq

How can I make a Linq query to grab ALL Productpricediscounts from a category?

public class ProductCategory
{
    public List<Product> categoryProducts;
}

public class Product
{
    public List<Productprice> productPrices;
}

public class Productprice
{
    public List<Productpricediscount> priceDiscounts;
}

My query has to look something like:

categoryProducts.Select(p => p.productPrices).Select(x => x.?!?!

The problem is that I would have expected the x. - intellisense to suggest priceDiscounts, but I get "list"-values (like: "Any", "Select", "Distinct" and so on.)

like image 619
David Avatar asked Nov 05 '09 11:11

David


People also ask

What is difference between select and SelectMany in Linq?

Select and SelectMany are projection operators. A select operator is used to select value from a collection and SelectMany operator is used to selecting values from a collection of collection i.e. nested collection.

What is SelectMany in Linq C#?

What is Linq SelectMany? The SelectMany in LINQ is used to project each element of a sequence to an IEnumerable<T> and then flatten the resulting sequences into one sequence. That means the SelectMany operator combines the records from a sequence of results and then converts it into one result.

How use any in Linq C#?

The C# Linq Any Operator is used to check whether at least one of the elements of a data source satisfies a given condition or not. If any of the elements satisfy the given condition, then it returns true else return false. It is also used to check whether a collection contains some data or not.


2 Answers

You'll need to use SelectMany in order to access priceDiscounts:

var query = categoryProducts
            .SelectMany(x => x.productPrices)
            .SelectMany(y => y.priceDiscounts);
like image 96
LukeH Avatar answered Oct 14 '22 17:10

LukeH


You need Enumerable.SelectMany

var result = categoryProducts.SelectMany(x => x.productPrices)
             .SelectMany(x => x.priceDiscounts);
like image 29
Winston Smith Avatar answered Oct 14 '22 15:10

Winston Smith