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
, otherwise false
.
Any idea?
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With