下面是我的代码的摘录:
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循环打印列表中的所有元素:
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循环。有没有更短/更好的方法?
发布于 2009-08-07 20:55:31
如果您只想访问列表中的最后一项,您可以这样做
if(integerList.Count>0)
{
// pre C#8.0 : var item = integerList[integerList.Count - 1];
// C#8.0 :
var item = integerList[^1];
}
要获取列表中的项目总数,可以使用Count
属性
var itemCount = integerList.Count;
发布于 2020-01-09 07:22:31
在C# 8.0中,可以使用^运算符full explanation获取最后一项
List<char> list = ...;
var value = list[^1];
// Gets translated to
var value = list[list.Count - 1];
发布于 2012-10-27 18:25:45
让我们来看看问题的根源,如何安全地处理列表的最后一个元素……
假设
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 )。此函数从列表的末尾开始,因此将是Big O(1)或constant time,尽管方法通常为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);
如果算上委托部分,FindLast方法就很难看,但它只需要在一个地方声明。如果列表为空,它将为字符串返回列表类型"“的默认构造值。将alwaysTrue委托更进一步,使其成为模板而不是字符串类型,会更有用。
https://stackoverflow.com/questions/1246918
复制相似问题