首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何找到List<>中的最后一个元素?

如何找到List<>中的最后一个元素?
EN

Stack Overflow用户
提问于 2009-08-07 20:48:09
回答 10查看 531.1K关注 0票数 221

下面是我的代码的摘录:

代码语言:javascript
复制
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()函数代码中使用以下代码:

代码语言:javascript
复制
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循环打印列表中的所有元素:

代码语言:javascript
复制
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,并打印出List中的所有条目。列表中的每个元素都是上面代码示例中提到的AllIntegerIDs类的一个对象。如何找到列表中的最后一个有效条目?

我应该使用像integerList.Find(integerList[].m_MessageText == null;这样的东西吗

如果我使用它,它将需要一个从0到任何最大值的索引。这意味着我将不得不使用另一个我不打算使用的for循环。有没有更短/更好的方法?

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1246918

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档