0

I have an array of numbers:

int[] array = new int[]{ 18, 5, 10, 12, 15, 18 };

how do I count all numbers above a certain level (without repetitions)? will LINQ be any help?

For example - there are 3 numbers above 10 (18,and 15, 12).

there's only 1 number above 15 (18,18 are practically the same number).

edit: (sorry forgot about this one)

is it possible to count repetitions above a certain level?

i.e. in my example with "15" there will be 2 repetitions

edit 2

my way of "grouping"

int count1 = array.Where(x => x > 15).Distinct().Count();
int count2 = array.Where( x => x > 15).Count();
int count3 = count2 - count1;
Alex
  • 4,607
  • 9
  • 61
  • 99

3 Answers3

6
int count = array.Where(x => x > 15).Distinct().Count();
ionden
  • 12,536
  • 1
  • 45
  • 37
2

Further for counting numbers in group:

int[] array = { 1, 2, 3, 44, 55, 66, 44, 1 };

            var x = array.GroupBy(t => t).Where(g => g.Key > 10).Select(g=>
                                                                          new {
                                                                              Number = g.Key,
                                                                              Count = g.Count()
                                                                            });

          foreach (var n in x)
          {
              Console.WriteLine("Number{0}\nCounts:{1}", n.Number, n.Count);
          }
Shivraj
  • 263
  • 1
  • 2
  • 8
  • unfortunatelly I coulldn't find a way to make work Grouping, so I did this: int count1 = array.Where(x => x > 15).Distinct().Count(); int count2 = array.Where( x => x > 15).Count(); int count3 = count2 - count1; but thank you for your solution too – Alex Mar 17 '12 at 08:47
0

Counting minus duplicates (outputs 4):

int[] array = new int[] { 18, 5, 10, 12, 15, 18 };
int count = array.Where(i => i > 10).Distinct().Count();

Counting duplicates (outputs 2: 18 & 18)

int duplicateCount = array.Where(w => w > 10).GroupBy(g => g).Where(w => w.Count() > 1).SelectMany(s => s).Count();

Or your cool solution of:

int count1 = array.Where(x => x > 10).Distinct().Count();
int count2 = array.Where(x => x > 10).Count();
int count3 = count2 - count1;

References:
Remove duplicates from array
Remove duplicates from a List<T> in C#
how to find and print the duplicates values in array in c#?
How to Count Duplicates in List with LINQ

Community
  • 1
  • 1
Nathan Goings
  • 1,145
  • 1
  • 15
  • 33
  • nice! Although I haven't noticed any performance difference between two methods (duplicate count) - I'll use your method because it's 1-line-long ;) – Alex Mar 17 '12 at 10:19