2013-02-27 4 views
1

계산이 포함 된 문자열이 있습니다. 각 항목은 다음 항목 사이에 공백이 있습니다. 최근 20 개의 항목 만 보관하려면 어떻게합니까?문자열의 처음 20 개 항목 만 유지하십시오.

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

출력은 다음과 같습니다

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

+0

지적대로? – MikeSmithDev

+0

최신 항목은 마지막에 붙습니다. – rupes0610

답변

3

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

또는 다윗 & Groo 다른 의견은 "가장 최근"간주되는

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

+0

Label2.Text = string.Split (''). 역행(). Take (20); 결과는 CS0120입니다 : 비 정적 필드, 메소드 또는 속성 'string.Split (params char [])'에 객체 참조가 필요합니다. – rupes0610

+0

예에서 처리하려는 문자열로'string'을 대체하십시오 – paul

1

가장 최근의가에있는 경우 문자열

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

을 분할 사용 끝까지 사용하면 OrderByDescending을 사용할 수 있습니다. Take20

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

.. 배열을 가져오고 가장 최근에 입력하지 않은 처음 20 개를 취합니다. 2 –

+0

'가장 최근'의 의미를 정의 할 수 있습니까? 이게 문자열의 끝인가요? – happygilmore

+3

'string.Split (''). 역행(). Take (20)'? – paul

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

관련 문제