Question

J'essaie de savoir combien de fois la valeur maximale d'un tableau survient dans le tableau en utilisant .Count () avec un prédicat à l'intérieur. Cependant, je ne comprends pas vraiment comment le faire. En lisant le maigre exemple de MSDN, je pensais avoir compris, mais apparemment pas!

Voici ce à quoi je pensais:

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

Mais cela n'a pas fonctionné. J'ai donc essayé de changer max en un entier pour voir si cela fonctionnerait, mais cela ne fonctionnait pas non plus.

Était-ce utile?

La solution

Vous pouvez utiliser la fonction Où pour filtrer en premier puis compter:

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

Autres conseils

Utilisation de Nombre (prédicat) est ok Vous avez juste besoin de convertir la valeur de retour (qui est un entier) en chaîne.

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

Maintenant, vous avez le compte qui est votre compte final. Donne plus de sens avec une collection int. Maintenant, pour l'afficher, vous pouvez simplement appeler ToString ().

Essayez quelque chose comme:

Label1.Text = test.Where(t => t == test.Max()).Count().ToString();
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top