2013-02-27 69 views
1

我有一個包含計算的字符串。每個條目之間都有一個空格。我如何只保留最近的20個參賽作品?只保留第一個20個條目中的字符串

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

輸出是:

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

+0

什麼被認爲是 「最近」 指出? – MikeSmithDev 2013-02-27 16:44:52

+0

最後的條目結尾 – rupes0610 2013-02-27 16:55:16

回答

3

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

或者,正如大衛& Groo在其他評論

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

+0

Label2.Text = string.Split(」「).Reverse()取(20);結果CS0120:非靜態字段,方法或屬性'string.Split(params char [])' – rupes0610 2013-02-27 17:22:15

+0

需要對象引用是的,在示例中,用要處理的字符串替換字符串 – paul 2013-02-28 13:38:54

1

使用字符串分割

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

如果最近的是在那麼你可以使用OrderByDescending然後Take20

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

..給出一個數組,並採取前20個,不是最近輸入的20個 – 2013-02-27 16:44:00

+0

你能定義什麼是'最近'的意思呢。這是字符串的結尾嗎? – happygilmore 2013-02-27 16:44:52

+3

'string.Split(」「).Reverse()。以(20)'? – paul 2013-02-27 16:45:12

1
string[] calculations = yourString.Split(' '); 
string[] last20 = calculations.Skip(Math.Max(0, calculations.Count() - 20).Take(20); 
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(不過這是以防萬一故障安全隊列正在從多個地方更新)。

另外,我不知道如果一個Label真的是保持項目列表的權限控制?

+0

+1我真的很喜歡這個效率的答案。 。 – itsme86 2013-02-27 17:15:13

相關問題