1

我有一个包含计算的字符串。每个条目之间都有一个空格。如何只保留最近的 20 个条目?

Label2.text += TextBox1.Text + "+" + TextBox2.Text + "=" + Label1.Text + " ";

输出是:

20+20=40 40+20=60 60+20=80

4

4 回答 4

3

您可能想要维护一个项目队列(先进先出结构):

// have a field which will contain calculations
Queue<string> calculations = new Queue<string>();

void OnNewEntryAdded(string entry)
{
    // add the entry to the end of the queue...
    calculations.Enqueue(entry);

    // ... then trim the beginning of the queue ...
    while (calculations.Count > 20)
        calculations.Dequeue();

    // ... and then build the final string
    Label2.text = string.Join(" ", calculations);
}

请注意,while循环可能只运行一次,并且可以很容易地替换为if(但这只是一个故障保险,以防队列从多个位置更新)。

另外,我想知道 aLabel是否真的是保存项目列表的正确控件?

于 2013-02-27T16:53:47.650 回答
3

string.Split(' ').Reverse().Take(20)

或者,正如 David & Groo 在其他评论中指出的那样

string.Split(' ').Reverse().Take(20).Reverse()

于 2013-02-27T16:55:53.650 回答
1

使用字符串拆分

string.Split(' ').Take(20)

如果最近的在最后,那么你可以使用OrderByDescendingthenTake20

string.Split(' ').Select((n, i) => new { Value = n, Index = i }).OrderByDescending(i => i.Index).Take(20);
于 2013-02-27T16:43:23.360 回答
1
string[] calculations = yourString.Split(' ');
string[] last20 = calculations.Skip(Math.Max(0, calculations.Count() - 20).Take(20);
于 2013-02-27T16:45:29.197 回答