将 C# Count() 与函数结合使用
我试图通过使用 Linq 的 .Count()
内部有谓词。但是,我不完全明白该怎么做。通过阅读 MSDN 的少量示例,我以为我理解了,但显然没有!
我是这么想的:
string[] test = { "1", "2", "3", "4", "4" };
string max = test.Max();
Label1.Text = test.Count(p => p == max);
但这并不起作用。因此,我尝试将 max 更改为整数,看看这是否有效,但这也不起作用。
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用
Count(predicate)
就可以了。您只需将返回值(整数)转换为字符串即可。Using
Count(predicate)
is OK. You just need to convert the return value (which is an integer) to string.您可以使用Where函数先过滤然后计数:
You could use the Where function to filter first then count:
现在您已经得到了最终计数。使用 int 集合更有意义。现在要显示它,您只需在计数时调用 ToString() 即可。
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: