C# 如何找到 List<> 中的最后一个元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1246918/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I find the last element in a List<> ?
提问by zack
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;
}
I am trying to use the following in my main() function code:
我试图在我的 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;
}
Problem is here: I am trying to print all elements in my List using a for loop:
问题在这里:我正在尝试使用 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);
}
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?
我想找到最后一个元素,以便在 for 循环中等同于 cnt3 并打印出列表中的所有条目。列表中的每个元素都是上面代码示例中提到的 AllIntegerIDs 类的对象。如何找到列表中的最后一个有效条目?
Should I use something like integerList.Find(integerList[].m_MessageText == null;
我应该使用像 integerList.Find(integerList[].m_MessageText == null; 之类的东西吗?
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?
如果我使用它,它将需要一个范围从 0 到任何最大值的索引。意味着我将不得不使用另一个我不打算使用的 for 循环。有没有更短/更好的方法?
Thanks, Viren
谢谢,维伦
采纳答案by Jared
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];
}
to get the total number of items in the list you can use the Count property
要获取列表中的项目总数,您可以使用 Count 属性
var itemCount = integerList.Count;
回答by Eric J.
Change
改变
for (int cnt3 = 0 ; cnt3 <= integerList.FindLastIndex ; cnt3++)
to
到
for (int cnt3 = 0 ; cnt3 < integerList.Count; cnt3++)
回答by Brandon
Why not just use the Count property on the List?
为什么不直接使用 List 上的 Count 属性?
for(int cnt3 = 0; cnt3 < integerList.Count; cnt3++)
回答by Spencer Ruport
Use the Count
property. The last index will be Count - 1
.
使用Count
物业。最后一个索引将是Count - 1
。
for (int cnt3 = 0 ; cnt3 < integerList.Count; cnt3++)
回答by Dan Diplo
int lastInt = integerList[integerList.Count-1];
回答by Michael Ciba
I would have to agree a foreach would be a lot easier something like
我不得不同意 foreach 会容易得多,例如
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.
此外,我建议您添加属性来访问您的信息而不是公共字段,根据您的 .net 版本,您可以添加它,public int MessageType {get; set;}
并m_
从您的公共字段、属性等中删除它,因为它不应该在那里。
回答by dahlbyk
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
循环中:
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);
}
回答by JFDev
Lets get at the root of the question, how to address the last element of a List safely...
让我们来看看问题的根源,如何安全地处理 List 的最后一个元素......
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.
“count-1”是一个坏习惯,除非你首先保证列表不为空。
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).
您可以全力以赴制作一个始终返回true的委托,并将其传递给FindLast,它将返回最后一个值(如果列表为空,则返回默认构造的valye)。该函数从列表的末尾开始,因此将是大 O(1) 或常量时间,尽管该方法通常是 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.
如果计算委托部分,FindLast 方法很丑陋,但它只需要声明一处。如果列表为空,它将为字符串返回列表类型“”的默认构造值。将 alwaysTrue 委托更进一步,使其成为模板而不是字符串类型会更有用。
回答by Kundan Singh Chouhan
To get the last item of a collection use LastOrDefault()and Last()extension methods
要获取集合的最后一项,请使用LastOrDefault()和Last()扩展方法
var lastItem = integerList.LastOrDefault();
OR
或者
var lastItem = integerList.Last();
Remeber to add using System.Linq;
, or this method won't be available.
记得添加using System.Linq;
,否则此方法将不可用。
回答by Muhammad Aasharib Nawshad
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
然后你可以索引 count - 1 以获取列表中的最后一个元素,例如
int lastNumber = list[count - 1];