简体   繁体   中英

How to find the second greatest element in a list with LINQ

Suppose we have a class (SomeClass) with two fields, an ID of type int and a date of type DateTime.

Now imagine that there is a list of SomeClass ordered by date and we need to find the second to last element of the list. How would we do this with LINQ ?

var nextToLast = list.Skip(list.Count - 2).First();

正如@Brizio指出的那样,您也可以使用良好的索引

var nextToLast = list[list.Count - 2];

Here is one for the second place:

In your comparison:

public class YourCustomClassComparer : IComparer<YourObject> {
    public int Compare(YourObject x, YourObject y) {
        //do whatever you need to do to compare
    }
}

and your method (this will grab the second in the list)

var result = list.OrderBy(a => a, new YourCustomClassCompairer()).ElementAt(1);

And if you wanted the inverse (which i noticed in your question), do the following

var result = list.OrderByDescending(a => a, new YourCustomClassCompairer()).ElementAt(1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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