Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Select Distinct Count in Lambda form

Given a linq expression of an object collection 'items' such as this:

var total = (from item in items select item.Value).Distinct().Count()

Is it possible to convert this to use linq functions/lambdas:

items.Select(???).Distinct().Count()
like image 207
Kyle Avatar asked Jul 07 '11 11:07

Kyle


2 Answers

Use this:

items.Select(i => i.Value).Distinct().Count()
like image 127
Daniel Hilgarth Avatar answered Oct 21 '22 10:10

Daniel Hilgarth


It must be possible, since behind the scenes, LINQ is translated to lambdas and expression trees (at least LINQ to objects)

In your case the ??? part would be item => item.Value, i.e. for item, output item.value. So, the whole expression will be

var total = items.Select(item => item.Value).Distinct().Count();
like image 11
SWeko Avatar answered Oct 21 '22 10:10

SWeko