LINQ Select Distinct Count in Lambda form

匿名 (未验证) 提交于 2019-12-03 02:54:01

问题:

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

回答1:

Use this:

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


回答2:

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


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!