将 C# Count() 与函数结合使用

发布于 2024-08-04 16:40:23 字数 450 浏览 5 评论 0原文

我试图通过使用 Linq 的 .Count() 内部有谓词。但是,我不完全明白该怎么做。通过阅读 MSDN 的少量示例,我以为我理解了,但显然没有!

我是这么想的:

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

但这并不起作用。因此,我尝试将 ma​​x 更改为整数,看看这是否有效,但这也不起作用。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

潜移默化 2024-08-11 16:40:23

使用 Count(predicate) 就可以了。您只需将返回值(整数)转换为字符串即可。

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

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();
面犯桃花 2024-08-11 16:40:23

您可以使用Where函数先过滤然后计数:

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

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

Label1.Text = test.Where(p => p == max).Count().ToString();
帅气称霸 2024-08-11 16:40:23
        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());

现在您已经得到了最终计数。使用 int 集合更有意义。现在要显示它,您只需在计数时调用 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.

〗斷ホ乔殘χμё〖 2024-08-11 16:40:23

尝试类似的方法:

Label1.Text = test.Where(t => t == test.Max()).Count().ToString();

Try something like:

Label1.Text = test.Where(t => t == test.Max()).Count().ToString();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文