check if record is last or first in list with linq
Solution 1
You can wrtie an extension method such as
public static class IEnumerableExtensions
{
public static bool IsLast<T>(this IEnumerable<T> items, T item)
{
var last = items.LastOrDefault();
if (last == null)
return false;
return item.Equals(last); // OR Object.ReferenceEquals(last, item)
}
public static bool IsFirst<T>(this IEnumerable<T> items, T item)
{
var first = items.FirstOrDefault();
if (first == null)
return false;
return item.Equals(first);
}
public static bool IsFirstOrLast<T>(this IEnumerable<T> items, T item)
{
return items.IsFirst(item) || items.IsLast(item);
}
}
You can use it like
IEnumerable<User> users = // something
User user = // something
bool isFirstOrLast = users.IsFirstOrLast(user);
Solution 2
If your list of objects is indeed a List
, it might be better to use it explicitly (adapted the Mehmet Ataş's answer):
static class ListExtensions
{
public static bool IsFirst<T>(this List<T> items, T item)
{
if (items.Count == 0)
return false;
T first = items[0];
return item.Equals(first);
}
public static bool IsLast<T>(this List<T> items, T item)
{
if (items.Count == 0)
return false;
T last = items[items.Count-1];
return item.Equals(last);
}
}
This way you eliminate the LINQ overhead (it's not much, but it's significant). However, your code must use List<T>
for this to work.
Solution 3
var yourObject = yourList[0];
if(list.Count > 0)
if(yourObject == list.First() || yourobject == list.Last())
{
//item is either first or last
}
But remember to check if the list contains atleast 1 item, otherwise you will end up with exception from First, Last.
The above will compare the reference for the objects, you can compare their values by implementing a custom IComparable or you may compare their values.
Related videos on Youtube
Laziale
Updated on September 15, 2022Comments
-
Laziale over 1 year
I have a list of objects. I want to determine when the user will get the first or last object in the list, that way I can disable some buttons on the page.
For example I might have some boolean and if the object requested is last or first in the list, then it will return
true
, otherwisefalse
.Any idea?
-
spender about 11 years...also worth being aware that in most/all cases,
.Last()
causes a full enumeration of the source sequence. -
SWeko about 11 yearsIf the
IEnumerable
is indeed aList
,Last()
will just returnlist[list.Count-1]
-
spender about 11 yearsUsed indiscriminately, this might have disastrous performance characteristics... for instance, called in a loop.
-
spender about 11 yearsMight also lead to false positives if the first/last item is not distinct in the sequence