我有一个包含整数的列表,所有整数都从 0 到 2。现在我必须检查这些数字中的任何一个是否恰好出现 3 次。那怎么查呢?
例子:
{ 2, 1, 0, 0, 1, 0 } //this is true
{ 1, 1, 2, 0, 0 } //this is false
{ 0, 0, 0, 1, 1, 1, 2, 2, 2 } //this is true
Run Code Online (Sandbox Code Playgroud)
您可以为此使用 LINQ:
bool containsNum3x =
list
.GroupBy(i => i) // group the 0s into a subset, the 1s into a subset, etc
.Any(s => s.Count() == 3); // check if the size of any subset is exactly 3
Run Code Online (Sandbox Code Playgroud)
文档:
您可能需要using System.Linq在代码文件的顶部按顺序添加。
| 归档时间: |
|
| 查看次数: |
59 次 |
| 最近记录: |