Check if entry is last or first in the list with linq
I have a list of objects . I want to detect when the user gets the first or last item in the list so that I can disable some of the buttons on the page.
For example, I might have some boolean value, and if the requested object is the last or first in the list, then it will return true
, otherwise false
.
Any idea?
source to share
You can use extension method like
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);
source to share
If your list of objects really is List
, it's better to use it explicitly (adapted from Mehmet Atash'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 LINQ overhead (not much, but important). However, your code must use List<T>
.
source to share
var yourObject = yourList[0];
if(list.Count > 0)
if(yourObject == list.First() || yourobject == list.Last())
{
//item is either first or last
}
But don't forget to check if the list contains at least 1 element , otherwise you will get an exception from First , Last .
The above will compare reference for objects, you can compare their values by embedding IComparable or you can compare their values,
source to share