Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using C# Count() with a function

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.

like image 976
Psytronic Avatar asked Sep 18 '09 13:09

Psytronic


2 Answers

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();
like image 187
mmx Avatar answered Oct 18 '22 21:10

mmx


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

Label1.Text = test.Where(p => p == max).Count().ToString();
like image 31
JDunkerley Avatar answered Oct 18 '22 21:10

JDunkerley