tags:

views:

431

answers:

4

I'm trying to see how many times the maximum value of an array occurs within the array by using .Count() with a function inside. However I don't fully understand how to do it. From reading the MSDN's scant example I thought I understood, however apparently not!

This is what I thought of:

string[] test = { "1", "2", "3", "4", "4" };
string max = test.Max();
Label1.Text = test.Count(p => p == max);

But that does not work, so I tried changing max to an int to see if that would work, and it did not either.

+3  A: 

You could use the Where function to filter first then count:

Label1.Text = test.Where(p => p == max).Count().ToString();
JDunkerley
Add a ToString() at the end....
BFree
@BFree: good point!
JDunkerley
You don't **need** filtering with `Where` first. `Count` has an overload that takes a `Func<T, bool>` predicate and only counts the matching items.
Mehrdad Afshari
@Mehrdad: didn't know that, would use your answer then
JDunkerley
A: 

Try something like:

Label1.Text = test.Where(t => t == test.Max()).Count().ToString();
Justin Niessner
+9  A: 

Using Count(predicate) is OK. You just need to convert the return value (which is an integer) to string.

Label1.Text = test.Count(p => p == max).ToString();
Mehrdad Afshari
+2  A: 
        int[] test = { 2, 45, 3, 23, 23, 4, 2, 1, 1, 1, 1, 23, 45, 45, 45 };
        int count = test.Count(i => i == test.Max());

Now you have the count which is your final count. Makes more sense with an int collection. Now to display it, you can just call ToString() on count.

BFree