How can I find the last element in a List<>?

后端 未结 13 1312
离开以前
离开以前 2020-12-12 21:43

The following is an extract from my code:

public class AllIntegerIDs 
{
    public AllIntegerIDs() 
    {            
        m_MessageID = 0;
        m_Messa         


        
相关标签:
13条回答
  • 2020-12-12 21:58

    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.

    0 讨论(0)
  • 2020-12-12 22:00

    I think this helps you. Please check

        TaxRangers[TaxRangers.Count]. max
    
    0 讨论(0)
  • 2020-12-12 22:01

    Change

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

    to

    for (int cnt3 = 0 ; cnt3 < integerList.Count; cnt3++)
    
    0 讨论(0)
  • 2020-12-12 22:02
    int lastInt = integerList[integerList.Count-1];
    
    0 讨论(0)
  • 2020-12-12 22:09

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

    for (int cnt3 = 0 ; cnt3 < integerList.Count; cnt3++)
    
    0 讨论(0)
  • 2020-12-12 22:09

    Though this was posted 11 years ago, I'm sure the right number of answers is one more than there are!

    You can also doing something like;

    
    if (integerList.Count > 0) 
       var item = integerList[^1];
    
    

    See the tutorial post on the MS C# docs here from a few months back.

    I would personally still stick with LastOrDefault() / Last() but thought I'd share this.

    EDIT; Just realised another answer has mentioned this with another doc link.

    0 讨论(0)
提交回复
热议问题