仅保留字符串中的前20个条目

时间:2013-02-27 16:42:15

标签: c# asp.net

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

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

输出是:

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

4 个答案:

答案 0 :(得分: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轻松替换(但这只是一个故障保护,以防从多个位置更新队列)。< / p>

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

答案 1 :(得分:3)

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

或者,正如David&amp; Groo在其他评论中指出了

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

答案 2 :(得分:1)

使用字符串拆分

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

如果最近一次是在最后,那么您可以使用OrderByDescending然后使用Take20

string.Split(' ').Select((n, i) => new { Value = n, Index = i }).OrderByDescending(i => i.Index).Take(20);

答案 3 :(得分:1)

string[] calculations = yourString.Split(' ');
string[] last20 = calculations.Skip(Math.Max(0, calculations.Count() - 20).Take(20);
相关问题