Sab*_*zer 1 c# arrays counter loops
那么,用C#创建循环的好方法又简单又好呢?每次在某个数组中出现某个值时,都会在另一个数组中的计数器上加1?
例如我有这个:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication22
{
class Program
{
const int SIZE = 12;
static void Main(string[] args)
{
int[] numbers = new int[SIZE] {5, 5, 5, 7, 7, 7, 9, 7, 9, 9, 9, 1};
string[] letters = new string[SIZE] { "m", "m", "s", "m", "s", "s", "s", "m", "s", "s", "s", "s" };
int[] values = new int[SIZE] {15, 22, 67, 45, 12, 21, 24, 51, 90, 60, 50, 44};
string[] status = new string[SIZE] { "f", "m", "f", "a", "m", "f", "f", "f", "m", "f", "m", "f" };
int[] Count = new int[4];
int x = 0;
int i = 0;
for (i = 0; i < SIZE - 1; i++)
{
if (numbers[i] > 0 && numbers[i] < SIZE)
{
x = Count[i];
Count[x]++;
}
}
for (i = 0; i < 4; i++)
{
Console.WriteLine("{0}", Count[4]);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我只计算4个数字出现在numbers数组中的次数。有人建议我在第一个循环中使用该方法,但是它似乎不起作用,并会产生一个错误,指出索引在数组中超出范围。我想显示每个数字(5、7、9和1)出现在4行中的次数。
编辑:不使用LINQ或任何其他喜欢字典或类似的东西。
由于此部分,您将获得索引超出范围的错误:
for (i = 0; i < SIZE - 1; i++)
{
if (numbers[i] > 0 && numbers[i] < SIZE)
{
x = Count[i];
Run Code Online (Sandbox Code Playgroud)
请注意,您是通过迭代0到SIZE - 1(11)时,Count只有一个尺寸4。
但是,您可以使用LINQ轻松完成此任务。
int[] numbers = new int[SIZE] { 5, 5, 5, 7, 7, 7, 9, 7, 9, 9, 9, 1 };
var count = numbers
.GroupBy(e => e)
.Where(e => e.Count() == 4)
.Select(e => e.First());
Run Code Online (Sandbox Code Playgroud)
因此,它将数字按其值进行分组,然后我们将列表精简为仅包含4个组,然后选择每个组中的第一个,并留下ints 的集合。
这是使用字典存储数字计数的非基于LINQ的解决方案。
int[] numbers = new int[SIZE] { 5, 5, 5, 7, 7, 7, 9, 7, 9, 9, 9, 1 };
var dictionary = new Dictionary<int, int>();
var numbersWithFour = new List<int>();
foreach (var number in numbers)
{
if (dictionary.ContainsKey(number))
dictionary[number]++;
else
dictionary.Add(number, 1);
}
foreach (var val in dictionary)
{
if (val.Value == 4)
{
numbersWithFour.Add(val.Key);
}
}
Run Code Online (Sandbox Code Playgroud)
稍加修改,您就可以得到一些结果。
int[] numbers = new int[SIZE] { 5, 5, 5, 7, 7, 7, 9, 7, 9, 9, 9, 1 };
string[] letters = new string[SIZE] { "m", "m", "s", "m", "s", "s", "s", "m", "s", "s", "s", "s" };
int[] values = new int[SIZE] { 15, 22, 67, 45, 12, 21, 24, 51, 90, 60, 50, 44 };
string[] status = new string[SIZE] { "f", "m", "f", "a", "m", "f", "f", "f", "m", "f", "m", "f" };
// Set the size of Count to maximum value in numbers + 1
int[] Count = new int[9 + 1];
int x = 0;
int i = 0;
for (i = 0; i < SIZE - 1; i++)
{
if (numbers[i] > 0 && numbers[i] < SIZE)
{
// Use value from numbers as the index for Count and increment the count
Count[numbers[i]]++;
}
}
for (i = 0; i < Count.Length; i++)
{
// Check all values in Count, printing the ones where the count is 4
if (Count[i] == 4)
Console.WriteLine("{0}", i);
}
Run Code Online (Sandbox Code Playgroud)
输出:
7
9
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
44216 次 |
| 最近记录: |