Question

I'm trying to figure out how many times the maximum value of an array occurs within the array by using Linq's.Count() with a predicate inside. However, I don't fully understand how to do it. From reading the MSDN's scant example I thought I understood, but 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 did not work. So I tried changing max to an integer to see if that would work, but that did not work either.

Was it helpful?

Solution

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

Label1.Text = test.Where(p => p == max).Count().ToString();

OTHER TIPS

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

Try something like:

Label1.Text = test.Where(t => t == test.Max()).Count().ToString();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top