programing tip

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

itbloger 2020. 6. 10. 22:44
반응형

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


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

var item = integerList[integerList.Count - 1];

to get the total number of items in the list you can use the Count propery

var itemCount = integerList.Count;

To get the last item of a collection use LastOrDefault() and Last() extension methods

var lastItem = integerList.LastOrDefault();

OR

var lastItem = integerList.Last();

Remeber to add using System.Linq;, or this method won't be available.


Lets get at the root of the question, how to address the last element of a List safely...

Assuming

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

Then

//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" is a bad habit unless you first guarantee the list is not empty.

There is not a convenient way around checking for the empty list except to do it.

The shortest way I can think of is

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

you could go all out and make a delegate that always returns true, and pass it to FindLast, which will return the last value (or default constructed valye if the list is empty). This function starts at the end of the list so will be Big O(1) or constant time, despite the method normally being O(n).

//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);

The FindLast method is ugly if you count the delegate part, but it only needs to be declared one place. If the list is empty, it will return a default constructed value of the list type "" for string. Taking the alwaysTrue delegate a step further, making it a template instead of string type, would be more useful.


Change

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

to

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

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

Why not just use the Count property on the List?

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

Use the Count property. The last index will be Count - 1.

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

You can find it by first counting number of elements in the list e.g

int count = list.Count();

Then you can index the count - 1 to get last element in list e.g

int lastNumber = list[count - 1];

I would have to agree a foreach would be a lot easier something like

foreach(AllIntegerIDs allIntegerIDs in integerList)
{
Console.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}\n", allIntegerIDs.m_MessageID,
allIntegerIDs.m_MessageType,
allIntegerIDs.m_ClassID,
allIntegerIDs.m_CategoryID,
allIntegerIDs.m_MessageText);
}

Also I would suggest you add properties to access your information instead of public fields, depending on your .net version you can add it like public int MessageType {get; set;} and get rid of the m_ from your public fields, properties etc as it shouldnt be there.


Independent of your original question, you will get better performance if you capture references to local variables rather than index into your list multiple times:

AllIntegerIDs ids = new AllIntegerIDs();
ids.m_MessageID = (int)IntegerIDsSubstring[IntOffset];
ids.m_MessageType = (int)IntegerIDsSubstring[IntOffset + 1];
ids.m_ClassID = (int)IntegerIDsSubstring[IntOffset + 2];
ids.m_CategoryID = (int)IntegerIDsSubstring[IntOffset + 3];
ids.m_MessageText = MessageTextSubstring;
integerList.Add(ids);

And in your for loop:

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

I think this helps you. Please check

    TaxRangers[TaxRangers.Count]. max

참고URL : https://stackoverflow.com/questions/1246918/how-can-i-find-the-last-element-in-a-list

반응형