如何找到List<>中的最后一个元素? [英] How can I find the last element in a List<>?
问题描述
以下是我的代码的摘录:
The following is an extract from my code:
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()中使用以下内容
函数代码:
I am trying to use the following in my main()
function code:
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循环打印列表中的所有元素:
Problem is here: I am trying to print all elements in my List using a for loop:
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);
}
我想找到最后一个元素,以便将cnt3等同于我的for循环并打印出所有内容列表
中的条目。列表中的每个元素都是 AllIntegerIDs
类的对象,如上面的代码示例所述。如何在列表中找到最后一个有效条目?
I want to find the last element so that I equate cnt3 in my for loop and print out all entries in the List
. Each element in the list is an object of the class AllIntegerIDs
as mentioned above in the code sample. How do I find the last valid entry in the List?
我应该使用类似 integerList.Find(integerList []。m_MessageText == null;
?
如果我使用它,它将需要一个从0到最大值的索引,这意味着我将不得不使用另一个我不打算使用的for循环
If I use that it will need an index that will range from 0 to whatever maximum. Means I will have to use another for loop which I do not intend to use. Is there a shorter/better way?
推荐答案
如果只想访问列表中的最后一项,则可以执行
If you just want to access the last item in the list you can do
if(integerList.Count>0)
{
var item = integerList[integerList.Count - 1];
}
要获取列表中的项目总数,可以使用 Count
属性
to get the total number of items in the list you can use the Count
property
var itemCount = integerList.Count;
这篇关于如何找到List<>中的最后一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!