2014-07-14 4 views
0

문자열 목록이 있으며이 목록에 요소를 계속 추가하고 있습니다. 이 목록이 6 개의 요소 (인덱스 0에서 5까지)를 초과하지 않게하고 싶습니다. 따라서 일단 인덱스 [5]에 도달하면 목록을 확장하고 싶지는 않지만 목록의 시작 부분에 요소를 추가하거나 이와 유사한 작업을 수행하십시오. 어느 시점이든이 목록에 마지막으로 추가 된 항목별로 정렬 된 마지막 3 개의 항목을 인쇄합니다. 아래에서 시도했지만 코드가 엉뚱한 것이라고 생각합니다. 당신이 목록에서 마지막 사람이기 위하여 최신 항목을 원하는 경우이 코드 조각 후, 나는 UrlList[UrlList.Count - 1],UrlList[UrlList.Count - 2];,UrlList[UrlList.Count - 3] Pls는이문자열 목록에 추가 된 마지막 세 요소를 인쇄하십시오.

 if (UrlList.Count == 5) 
    { 
     var move = UrlList[5]; 
     UrlList.RemoveAt(5); 
     UrlList.Insert(0, move); 

     move = UrlList[4]; 
     UrlList.RemoveAt(4); 
     UrlList.Insert(1, move); 

     move = UrlList[3]; 
     UrlList.RemoveAt(3); 
     UrlList.Insert(2, move); 
     UrlList.Add(uri.ToString()); 
    } 

    else 
    { 
     UrlList.Add(uri.ToString()); 
    } 
+0

이 목록에 모든 시간을 3 개 항목을 추가하는 방법은 무엇입니까? 또는 언제든지 1-5를 추가 할 수 있습니까? –

+0

나는 목록에 1을 더한다. 그러나 한 번에 3을 인쇄한다 - 마지막 엘레멘트, 마지막 엘레멘트 -1, 마지막 엘름 -2 –

답변

2

좀 도와 목록 수와 인쇄를 얻을 것입니다, 당신은 사용할 수 있습니다 이 코드 :

const int Max_Capacity = 6; 

if (UrlList.Count >= Max_Capacity) 
    UrlList.RemoveAt(0); // <- oldest (first) item should be removed 

UrlList.Add(uri.ToString()); 

... 

// Printing out the lastest 3 items: 
int start = UrlList.Count <= 3 ? 0 : UrlList.Count - 3; 

for (int i = start; i < UrlList.Count; ++i) 
    Console.Out.WriteLine(UrlList[i]); 
0

% Operator-를 사용하는 것이 좋습니다. 귀하의 경우에는

당신은 사용할 수 있습니다

UrlList.Insert((UrlList.count%6),move); 
관련 문제