使用一个数组来跟踪3个数据

时间:2013-09-14 14:27:44

标签: c# arrays multidimensional-array

我需要你的帮助,使用一个数组来跟踪3个数据。我有一个数组,因为它是学校作业,我被要求这样做。 该阵列必须跟踪省份ID,区域ID和每个区域的人口。有13个省,每个省有48个地区。由于阵列是固定大小,我使用了624乘3多维数组。第一列用于省ID,第二列用于regionID,第三列用于人口..我将行设置为624,因为每个省有13个省和48个地区,因此13 * 48 = 624。 / p>

我能够插入我的数据并像这样显示它们

ProvinceID # 1 RegionID # 1: 125000

相反,我希望按省份显示地区和人口。

这样的事情:

ProvinceID #1

RegionID # 1: 12000
RegionID # 2: 30000

ProvinceID #2

RegionID #1: 14000
RegionID #: 145000

这就是我所做的 我宣布一个全局数组      int [,]人口普查;

我在表单初始化时初始化它      census = new int [624,3];

这是我的插入

try
{
    // declare variables
    int prov, region, population;

    prov = Convert.ToInt32(txtProvinceID.Text);
    region = Convert.ToInt32(txtRegionID.Text);
    population = Convert.ToInt32(txtPopulation.Text);


    census[counter, 0] = prov;
    census[counter, 1] = region;
    census[counter, 2] = population;

    counter++;

    MessageBox.Show("Population " + txtPopulation.Text.ToString() + " saved for Province #" + txtProvinceID.Text.ToString()
        + " , Region #" + txtRegionID.Text.ToString(), "Success!");

    txtRegionID.Clear();
    txtProvinceID.Clear();
    txtPopulation.Clear();
    txtProvinceID.Focus();
}
catch (Exception ex)
{
    if (ex.Message == "Input string was not in a correct format.")
    {
        MessageBox.Show("Please enter a numeric value", "Error");
    }
    else
    {
        MessageBox.Show(ex.Message, "Error");
    }
}

这是检索数据并将其保存到文件的代码

string output = "";

try
{
    for (int rows = 0; rows < census.GetLength(0); rows++)
    {

        for (int columns = 0; columns < census.GetLength(1); columns++)
        {
            if (census[rows, columns] != 0)
            {
                if (columns == 0)
                {
                    output += "Province ID #" + census[rows, columns];
                }
                else if (columns == 1)
                {
                    output += "Region ID #" + census[rows, columns] + ": ";
                }
                else if (columns == 2)
                {
                    output += census[rows, columns] + "\n";
                }

            }// END if census[rows, coloumns]!=0

        }// END for coloumns

    }//END for(int row =0

    // save the data to a text file

    SaveFileDialog sfd = new SaveFileDialog();
    sfd.FileName = "untitled";
    sfd.Filter = "Text (*.txt)|*.txt|Word Doc (*.doc)|*.doc";
    sfd.DefaultExt = "txt";
    sfd.AddExtension = true;
    sfd.ShowDialog();

    FileStream sf = new FileStream(sfd.FileName, FileMode.Create);

    StreamWriter sw = new StreamWriter(sf);

    sw.Write(output);

    sw.Close();
}
catch (Exception)
{

}

4 个答案:

答案 0 :(得分:2)

  

数组必须跟踪省份ID,区域ID和每个区域的人口。

这表示您应创建class来保存这三个数据。这样,使用数组将更容易。类似的东西:

class Region
{
    public int ProvinceId { get; set; }
    public int RegionId { get; set; }
    public long Population { get; set; }
}

请注意,我为群体选择了不同的类型,你不能用一个简单的数组来做这个,你肯定迟早会需要这样的东西。

如果有,可以使用LINQ创建来自同一省的区域组:

Region[] regions = …; // or maybe List<Region>

var regionGroups = regions.GroupBy(r => r.ProvinceId);

var result = new StringBuilder();

foreach (regionGroup in regionGroups)
{
    result.AppendFormat("Province ID #{0}\n\n", regionGroup.Key);

    foreach (var region in regionGroup)
    {
        result.AppendFormat(
            "Region ID #{0}: {1}\n", region.RegionId, region.Population);
    }
}

return result.ToString();

此外,你永远不应该这样做:

catch (Exception)
{
}

如果您需要处理某些特定异常,请处理这些异常,但仅处理

答案 1 :(得分:2)

考虑一个表,其中行是省,列是区域。在每个表格中,单元格是该省/地区的人口。它看起来像这样

            Region 1    Region 2    Region 3
Province 1   12000       13000       14000
Province 2   11320        9876        1234
Province 3   19723       32767        5038
Province 4     263        1284        1961

这完全对应于二维数组:

int[,] census = new int[4,3];

数组中的值将是,例如:

census[0,0] = 12000;  // Province 1, Region 1
census[0,1] = 13000;  // Province 1, Region 2
census[2,2] = 5038;   // Province 3, Region 3

修改您的代码,您将创建人口普查数据:

int[,] census = new int[13, 48];

并填充它:

prov = Convert.ToInt32(txtProvinceID.Text);
region = Convert.ToInt32(txtRegionID.Text);
population = Convert.ToInt32(txtPopulation.Text);
census[prov-1, region-1] = population;

现在,如果您想按省和地区输出:

StringBuilder output = new StringBuilder();
for (int prov = 0; prov < census.GetLength(0); prov++)
{
    output.AppendLine("Province ID " + prov+1);
    for (int region = 0; region < census.GetLength(1); ++region)
    {
        output.AppendLine("  Region #" + region+1 + " " +
            census[prov, region]);
    }
}

然后输出它,你打开文件并显示Write(output.ToString())

我使用StringBuilder构建输出而不是附加到string。附加字符串非常昂贵。

此外,您可以使用File.WriteAllText简化使用{{3}}编写文件的文件,如下所示:

// Show the Save File dialog box. And then,
File.WriteAllText(sfd.Filename, output.ToString());

无需打开FileStream,然后打开StreamWriterFile.WriteAllText为你照顾所有这些。

更新

要跳过没有数据的省份,请写入临时StringBuilder,然后仅在有数据的情况下将其附加到最终输出。例如:

StringBuilder output = new StringBuilder();
for (int prov = 0; prov < census.GetLength(0); prov++)
{
    StringBuilder sbTemp = new StringBuilder();
    for (int region = 0; region < census.GetLength(1); ++region)
    {
        if (census[prov, region] != 0)
        {
            sbTemp.AppendLine("  Region #" + region+1 + " " +
                census[prov, region]);
        }
    }
    if (sbTemp.Length > 0)
    {
        // At least one region had population, so add that
        // and the province to the output.
        output.AppendLine("Province ID " + prov+1);
        output.Append(sbTemp);
    }
}

答案 2 :(得分:0)

我认为用你当前的程序设计很难做到这一点

我建议您使用锯齿状数组来存储值,因为 LINQ不能在2D数组上使用

锯齿状数组是“数组数组”

string[][] census=new string[624][];

for(int i=0;i<624;i++)
{
census[i]=new string[3];
}

现在您可以使用LINQ从数组中获取所需的数据

var match=from c in census 
          where c[0]=="Province ID Text"
          from details in c
          where details!="Province ID Text"
          select details;

并按以下方式打印值

foreach(var i in match)
Console.WriteLine(i);

答案 3 :(得分:0)

如果您真的特别注意不使用对象或数据库表来存储值和 也不想使用LINQ,以下解决方案可能对您有所帮助

        void Select(string key)
        {
            for(int i=0;i<624;i++)
            {
                if(census[i][0]==key)
                {
                    Console.Write(census[i][1]);
                    Console.Write(census[i][2]);
                    Console.WriteLine();

                }

            }
        }

为了消除重复数据,我们使用List来检查先前是否检查过省Id

            string done = "";
            for (int i = 0; i < 624; i++)
            {
                if (!done.Contains(census[i][0]))
                {
                    Console.WriteLine(census[i][0]);
                    Select(census[i][0]);
                }
                done=done+census[i][0];
            }

我希望这段代码可以帮助你,但这不是一个很好的编程方法。