1

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);
3
  • What is s.id? How do you know that an element appears only once? Do you compare by reference or by s.id? Sep 16, 2016 at 17:21
  • Use Distinct method. Sep 16, 2016 at 17:23
  • 1
    @AlexanderPetrov The Distinct wouldn't give me elements that appear once.
    – Steven B.
    Sep 16, 2016 at 17:32

2 Answers 2

3

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();
2
  • From my quick testing, seems as if both yours and itsme86 answers work. Is there any significant difference between yours and his?
    – Steven B.
    Sep 16, 2016 at 17:31
  • Count() internally filters items and then count them, while in first one we are filtering and then counting, you can benchmark both for performance concerns Sep 16, 2016 at 17:37
1

You can use GroupBy():

int test = list.GroupBy(s => s.id).Count(g => g.Count() == 1);
4
  • From my quick testing, seems as if both yours and Ehsan Sajjad answers work. Is there any significant difference between yours and his?
    – Steven B.
    Sep 16, 2016 at 17:31
  • Just that mine avoids a Where() call by using the predicate in Count().
    – itsme86
    Sep 16, 2016 at 17:35
  • Count() internally filters items and then count them, while in first one we are filtering and then counting, you can benchmark both for performance concerns Sep 16, 2016 at 17:36
  • Bench marking would make a difference if there are millions of records to produce substantial difference Sep 16, 2016 at 18:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.