Reputation: 55
I have an array of objects with the property of ProductId
. I would like to use a lambda expression to select all the distinct values of ProductId
that are within my object array products
.
Here I get the products
var products = Database.SqlQuery<StructuredProduct>("query").ToArray();
And I can group by distinct values of ProductId, but it still returns an array of objects, rather than an array of ProductIds
var productIds= products.GroupBy(p => p.ProductId).Select(group => group.First()).ToArray();
Any idea on how to use a Lambda Expression on the products
array to get all distinct values of ProductIds
?
Upvotes: 3
Views: 3064
Reputation: 7111
I've only ever done GroupBy operations with the query comprehension syntax. If you do that, group
/ by
/ into
, the thing you group into has a property named key
. That would contain your 'productid`
var results = from product in products
group product by ProductId
into individualProducts
select individualProducts;
var productsArray = individualProducts.Select(p => p.Key).ToArray();
The items individualProducts
collection each have a Key
and a collection of things that have the same productid.
If you do this directly out of the database, all your operations will get nicely combined into a single SQL statement that will get executed when your code gets to .ToArray()
Upvotes: 1
Reputation: 2797
With LINQ method .Distinct()
var productIds = products.Select(p => p.ProductId).Distinct();
Upvotes: 4
Reputation: 415860
var productIds= products.Select(p => p.ProductId).Distict();
But it may be even better to do this directly on the database, as part of the "query"
sql command.
Upvotes: 9