Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if record is last or first in list with linq

Tags:

c#

asp.net

linq

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?

like image 343
Laziale Avatar asked Dec 05 '22 12:12

Laziale


2 Answers

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.

like image 183
SWeko Avatar answered Dec 13 '22 20:12

SWeko


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);
like image 39
Mehmet Ataş Avatar answered Dec 13 '22 21:12

Mehmet Ataş