[C#] List <>에서 마지막 요소를 어떻게 찾을 수 있습니까?

다음은 내 코드에서 추출한 것입니다.

public class AllIntegerIDs 
{
    public AllIntegerIDs() 
    {            
        m_MessageID = 0;
        m_MessageType = 0;
        m_ClassID = 0;
        m_CategoryID = 0;
        m_MessageText = null;
    }

    ~AllIntegerIDs()
    {
    }

    public void SetIntegerValues (int messageID, int messagetype,
        int classID, int categoryID)
    {
        this.m_MessageID = messageID;
        this.m_MessageType = messagetype;
        this.m_ClassID = classID;
        this.m_CategoryID = categoryID;
    }

    public string m_MessageText;
    public int m_MessageID;
    public int m_MessageType;
    public int m_ClassID;
    public int m_CategoryID;
}

내 main () 함수 코드에서 다음을 사용하려고합니다.

List<AllIntegerIDs> integerList = new List<AllIntegerIDs>();

/* some code here that is ised for following assignments*/
{
   integerList.Add(new AllIntegerIDs());
   index++;
   integerList[index].m_MessageID = (int)IntegerIDsSubstring[IntOffset];
   integerList[index].m_MessageType = (int)IntegerIDsSubstring[IntOffset + 1];
   integerList[index].m_ClassID = (int)IntegerIDsSubstring[IntOffset + 2];
   integerList[index].m_CategoryID = (int)IntegerIDsSubstring[IntOffset + 3];
   integerList[index].m_MessageText = MessageTextSubstring;
}

문제는 여기에 있습니다 : for 루프를 사용하여 List의 모든 요소를 ​​인쇄하려고합니다.

for (int cnt3 = 0 ; cnt3 <= integerList.FindLastIndex ; cnt3++) //<----PROBLEM HERE
{
   Console.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}\n", integerList[cnt3].m_MessageID,integerList[cnt3].m_MessageType,integerList[cnt3].m_ClassID,integerList[cnt3].m_CategoryID, integerList[cnt3].m_MessageText);
}

마지막 요소를 찾아서 for 루프에서 cnt3을 동일하게하고 목록의 모든 항목을 인쇄하려고합니다. 목록의 각 요소는 코드 샘플에서 위에서 언급 한대로 AllIntegerID 클래스의 객체입니다. 목록에서 마지막으로 유효한 항목을 어떻게 찾습니까?

integerList.Find (integerList []. m_MessageText == null;

그것을 사용하면 0에서 최대 범위의 인덱스가 필요합니다. 내가 사용하지 않을 다른 for 루프를 사용해야한다는 것을 의미합니다. 더 짧거나 더 나은 방법이 있습니까?

고마워, Viren



답변

목록의 마지막 항목에 액세스하려면 할 수 있습니다

if(integerList.Count>0)
{
   var item = integerList[integerList.Count - 1];
}

목록의 총 항목 수를 얻으려면 Count 속성을 사용할 수 있습니다

var itemCount = integerList.Count;


답변

컬렉션의 마지막 항목을 얻으려면 LastOrDefault ()Last () 확장 메서드를 사용하십시오.

var lastItem = integerList.LastOrDefault();

또는

var lastItem = integerList.Last();

추가 using System.Linq;해야합니다.이 방법은 사용할 수 없습니다.


답변

질문의 근원, List의 마지막 요소를 안전하게 처리하는 방법에 대해 알아 보겠습니다.

가정

List<string> myList = new List<string>();

그때

//NOT safe on an empty list!
string myString = myList[myList.Count -1];

//equivalent to the above line when Count is 0, bad index
string otherString = myList[-1];

“count-1″은 목록이 비어 있지 않다는 것을 먼저 보증하지 않는 한 나쁜 습관입니다.

빈 목록을 확인하는 것 외에는 편리한 방법이 없습니다.

내가 생각할 수있는 가장 짧은 방법은

string myString = (myList.Count != 0) ? myList [ myList.Count-1 ] : "";

모두 나가서 항상 true를 반환하는 델리게이트를 만들고 FindLast에 전달하면 마지막 값 (또는 목록이 비어 있으면 기본으로 구성된 valye)이 반환됩니다. 이 함수는 목록의 끝에서 시작하므로 일반적으로 O (n) 인 방법에도 불구하고 Big O (1) 또는 상수 시간이됩니다.

//somewhere in your codebase, a strange delegate is defined
private static bool alwaysTrue(string in)
{
    return true;
}

//Wherever you are working with the list
string myString = myList.FindLast(alwaysTrue);

FindLast 메서드는 대리자 부분을 세면 추악하지만 한 곳으로 만 선언하면됩니다. 목록이 비어 있으면 문자열에 대해 목록 유형 “”의 기본 구성 값을 반환합니다. alwaysTrue 대리자를 한 단계 더 발전시켜 문자열 형식 대신 템플릿으로 만드는 것이 더 유용합니다.


답변

int lastInt = integerList[integerList.Count-1];


답변

변화

for (int cnt3 = 0 ; cnt3 <= integerList.FindLastIndex ; cnt3++)

for (int cnt3 = 0 ; cnt3 < integerList.Count; cnt3++)


답변

Count속성을 사용하십시오 . 마지막 색인은입니다 Count - 1.

for (int cnt3 = 0 ; cnt3 < integerList.Count; cnt3++)


답변

목록에서 먼저 요소 수를 세면 찾을 수 있습니다.

int count = list.Count();

그런 다음 count-1을 색인하여 목록의 마지막 요소를 얻습니다.

int lastNumber = list[count - 1];