简体   繁体   中英

Get a count of elements that appear once in a list with LINQ

Is it possible to get an integer count of elements that appear only once in a list with LINQ without creating a temporary list of those values and then counting that list?

Obviously this doesn't work but something like:

int test = list.Count(s => s.id).Where(s.id.Count() == 1);

You have to group them and the project the items which have count of 1 and then count the number of groups:

int test = list.GroupBy(s => s.id).
               .Where(g=> g.Count() == 1)
               .Count();

您可以使用GroupBy()

int test = list.GroupBy(s => s.id).Count(g => g.Count() == 1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM