Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select all distinct values of variable in object array using lambda expression

Tags:

c#

lambda

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?

like image 445
LRID Avatar asked Apr 14 '26 15:04

LRID


2 Answers

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.

like image 101
Joel Coehoorn Avatar answered Apr 16 '26 03:04

Joel Coehoorn


With LINQ method .Distinct()

var productIds = products.Select(p => p.ProductId).Distinct();
like image 37
T-moty Avatar answered Apr 16 '26 05:04

T-moty



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!