简体   繁体   English

如何找到 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;
}

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 .我想找到最后一个元素,以便在 for 循环中等同于 cnt3 并打印出List所有条目。 Each element in the list is an object of the class AllIntegerIDs as mentioned above in the code sample.列表中的每个元素都是上面代码示例中提到的AllIntegerIDs类的对象。 How do I find the last valid entry in the List?如何找到列表中的最后一个有效条目?

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.如果我使用它,它将需要一个范围从 0 到任何最大值的索引。 Means I will have to use another for loop which I do not intend to use.意味着我将不得不使用另一个我不打算使用的 for 循环。 Is there a shorter/better way?有没有更短/更好的方法?

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;记得using System.Linq;添加using System.Linq; , or this method won't be available. ,否则此方法将不可用。

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;

In C# 8.0 you can get the last item with ^ operator full explanation在 C# 8.0 中,您可以使用 ^ 运算符获取最后一项完整说明

List<char> list = ...;
var value = list[^1]; 

// Gets translated to 
var value = list[list.Count - 1];

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).您可以全力以赴制作一个始终返回true的委托,并将其传递给FindLast,它将返回最后一个值(如果列表为空,则返回默认构造的valye)。 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).该函数从列表的末尾开始,因此将是大 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.如果计算委托部分,FindLast 方法很丑陋,但它只需要声明一处。 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.将 alwaysTrue 委托更进一步,使其成为模板而不是字符串类型会更有用。

int lastInt = integerList[integerList.Count-1];

Change改变

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

to

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

Though this was posted 11 years ago, I'm sure the right number of answers is one more than there are!尽管这是 11 年前发布的,但我确信正确的答案数量比实际数量多一个!

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.看到在微软的C教程后#文档这里从几个月前。

I would personally still stick with LastOrDefault() / Last() but thought I'd share this.我个人仍然会坚持使用LastOrDefault() / Last()但我想我会分享这个。

EDIT;编辑; Just realised another answer has mentioned this with another doc link.刚刚意识到另一个答案在另一个文档链接中提到了这一点。

Use the Count property.使用Count属性。 The last index will be Count - 1 .最后一个索引将是Count - 1

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

You can find it by first counting number of elements in the list eg 您可以通过首先计算列表中元素的数量来找到它,例如

int count = list.Count();

Then you can index the count - 1 to get last element in list eg 然后你可以索引count - 1来获取列表中的最后一个元素,例如

int lastNumber = list[count - 1];

为什么不直接使用 List 上的 Count 属性?

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

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);
}

I think this helps you. 我认为这有助于你。 Please check 请检查

    TaxRangers[TaxRangers.Count]. max

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;}此外,我建议您添加属性来访问您的信息而不是公共字段,根据您的 .net 版本,您可以将其添加为public int MessageType {get; set;} public int MessageType {get; set;} and get rid of the m_ from your public fields, properties etc as it shouldnt be there. public int MessageType {get; set;}并从您的公共字段、属性等中删除m_ ,因为它不应该在那里。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM