检查记录是去年还是先与LINQ名单 [英] check if record is last or first in list with linq

查看:150
本文介绍了检查记录是去年还是先与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.

你知道吗?

推荐答案

您可以wrtie扩展方法,如

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);
    }
 }

您可以使用它像

 IEnumerable<User> users = // something
 User user = // something

 bool isFirstOrLast = users.IsFirstOrLast(user);

这篇关于检查记录是去年还是先与LINQ名单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆