How to find second last element from a List?
Starting with C# 8.0 you can use Index
to get access to elements relative to the end of sequence:
if (lsRelation.Count >= 2)
secLast = lsRelation[^2];
See docs for more information
If you know that's an IList<T>
which has an indexer:
string secondLast = null;
if (lsRelation.Count >= 2)
secondLast = lsRelation[lsRelation.Count - 2];
You could create an extension like:
public static T SecondLast<T>(this IEnumerable<T> items)
{
if (items == null) throw new ArgumentNullException("items");
IList<T> list = items as IList<T>;
if (list != null)
{
int count = list.Count;
if (count > 1)
{
return list[count - 2];
}
else
throw new ArgumentException("Sequence must contain at least two elements.", "items");
}
else
{
try
{
return items.Reverse().Skip(1).First();
} catch (InvalidOperationException)
{
throw new ArgumentException("Sequence must contain at least two elements.", "items");
}
}
}
Then you can use it in this way:
string secondLast = lsRelation.SecondLast();
Use:
if (lsRelation.Count >= 2)
secLast = lsRelation[lsRelation.Count - 2];