如何绘制存储在列表中的数组的内容?

时间:2014-04-30 11:23:24

标签: c# arrays list xna ienumerable

我的文件包含以下格式的分数:

000001,1
000002,2
000012,1
232124,1

我构建了一个数组,其中包含得分作为第一个元素,而难度作为第二个元素。然后我将数组添加到列表中:

// load highscores
public void LoadScores()
{
    StreamReader file = new StreamReader("highScores.txt");

    // loop through each line in the file
    while ((line = file.ReadLine()) != null)
    {
        // seperate the score from the difficulty
        lineData = line.Split(',');

        // add each line to the list
        list.Add(lineData);
    }
    OrderScores();

}

接下来,我使用IEnumerable

订购列表
IEnumerable<string[]> scoresDesNormal, scoresDesHard;

// order the list of highscores
protected void OrderScores()
{
    // order the list by descending order with normal difficulty at the top
    scoresDesNormal = list.OrderByDescending(ld => lineData[0]).Where(ld => lineData[1].Contains("1"));
    // order the list by descending order with hard difficulty at the top
    scoresDesHard = list.OrderByDescending(ld => lineData[0]).Where(ld => lineData[1].Contains("2")).Take(3);
}

现在,我想使用IEnumerable将两个spriteBatch.DrawString()列表打印到屏幕上。如何正确迭代列表元素和它们旁边的数组?我想打印出列表中存储的每个数组的两个元素。

2 个答案:

答案 0 :(得分:1)

首先,你的问题。

如果你知道如何绘制1个字符串,并且想要绘制2个字符串并在它们之间绘制分隔符&#34;,&#34;,只需执行以下操作:

...
string firstString = ...
string secondString = ...

string toBeDrawn = firstString + "," + secondString;
DrawThisFellah ( toBeDrawn );

...  

那么,你有一个string[]?没问题:

...
string[] currentElement = ...

string firstString = currentElement[0];
string secondString = currentElement[1];
// etc
...

其次,您不需要为字母OrderByDescending添加前导零来工作。您可以解析(并因此验证)字符串并将其存储在int[]类型的元素中,而不是string[]

THIRD ,这可能会让您感兴趣!

在不知道您使用LINQ的情况下使用它是危险的。 您是否知道IEnumerable<string[]>实际上是查询,对吧?

可以说你的IEnumerable<string[]>对象实际上是&#34;代码为数据&#34;。 它们包含而不是<{1}}的结果,而是逻辑本身。

这意味着如果你说OrderByDescending中有3 string[]个元素:

lineData

然后调用{ "1", "122" }, { "3", "42" }, { "5", "162" } ,然后在枚举OrderScores时会注意到结果(例如)。以下代码:

scoresDesNormal

将打印到控制台:

foreach (var element in scoresDesNormal)
    Console.WriteLine("{0}, {1}", element[0], element[1]);

(因为第二个元素在第二个子元素上没有&#39; 1&#39;字符)

,如果您继续修改1, 122 5, 162 集合,方法是插入新元素或删除元素(如果它是lineData),或者只是通过修改现有元素(如果它是一个原始数组),那么当枚举List<string[]> 而不调用scoresDesNormal时,您会观察到新的结果!

例如,以下代码的注释是真实的(假设您有OrderScores):

List<string[]> lineData

答案 1 :(得分:0)

如果我是你,我会这样做,

如果用户点击或按下按钮查看分数,请打开一个方法,如此。

public void DisplayScores()
{
Rectangle[] PositionOfText = new Rectangle[scoresDesNormal];
for (int i = 0; i< scoresDesNormal.Count; i++)
{
PositionOfText = new Rectangle(xPos, yPos, Width, Height);
}
//do the same for the other difficulties, this sets the position of the texts.

导入您要使用的fontbatch。 并且在你的绘制方法中有这样的东西,

for (int i = 0; i< scoresDesNormal.Count; i++)
spritebatch.drawString(MyFontBatch, scoresDesNormal[i], PositionOfText, Color.//your preffered color.

现在我可以理解他们可能是错误的,但我不是一个流利的c#程序员,但那或多或少你能做什么

相关问题