Kyle
Kyle

Reputation: 1365

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()

Upvotes: 31

Views: 36608

Answers (2)

SWeko
SWeko

Reputation: 30902

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();

Upvotes: 11

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174329

Use this:

items.Select(i => i.Value).Distinct().Count()

Upvotes: 53

Related Questions