SelectCount by Three options ObjectDataSource

时间:2012-02-16 02:46:34

标签: c# asp.net

我需要对GetUsers进行计数,但是通过alpha,search和byEmail参数我有3个不同的计算我在这种情况下可以为我的ObjectDataSource SelectCount方法做什么

public class Users
{
    public IList<MembershipUser> GetUsers(string alpha, string search, bool byEmail, int startRowIndex, int maximumRows)
    {
        IList<MembershipUser> users = null;

        if (alpha != null && search == null)
        {
            users = Membership.GetAllUsers().Cast<MembershipUser>().Where(x => x.UserName.StartsWith(alpha) == true).ToList();
        }
        else if (search != null && !byEmail)
        {
            users = Membership.FindUsersByName(search).Cast<MembershipUser>().Skip(maximumRows * startRowIndex).Take(maximumRows).ToList();
        }
        else
        {
            users = Membership.FindUsersByEmail(search).Cast<MembershipUser>().Skip(maximumRows * startRowIndex).Take(maximumRows).ToList();
        }

        return users;

    }

    public int GetUserCount()
    {

    }

更新了C#:

    public IEnumerable<MembershipUser> GetUsers(string alpha, string searchBy, string searchText, int startRowIndex, int maximumRows)
    {
        var users = Membership.GetAllUsers().Cast<MembershipUser>();

        if (alpha != null && string.IsNullOrEmpty(searchBy))
        {
            users = users
                .Where(x => x.UserName.StartsWith(alpha, StringComparison.OrdinalIgnoreCase))
                .Skip(maximumRows * startRowIndex)
                .Take(maximumRows).ToList();
        }
        else if (searchBy == "User Name" && !string.IsNullOrEmpty(searchText))
        {
            users = users.Where(x => x.UserName == searchText)
                .Skip(maximumRows * startRowIndex)
                .Take(maximumRows).ToList();
        }
        else if (searchBy == "Email" && !string.IsNullOrEmpty(searchText))
        {
            users = users.Where(x => x.Email == searchText)
                .Skip(maximumRows * startRowIndex)
                .Take(maximumRows).ToList();
        }
        else
        {
            users = null;
        }

        return users;

    }

1 个答案:

答案 0 :(得分:1)

以下内容应该有效:

public int GetUserCount(string alpha, string search, bool byEmail, int startRowIndex, int maximumRows)
{
    var users = Membership.GetAllUsers().Cast<MembershipUser>();

    if (alpha != null && search == null)
    {
        users = users.Where(x => x.UserName.StartsWith(alpha) == true);
    }
    else if (search != null && !byEmail)
    {
        users = users.FindUsersByName(search).Cast<MembershipUser>();
    }
    else
    {
        users = users.FindUsersByEmail(search);
    }

    return users.Count();
}

如果FindUsersByNameFindUsersByEmail返回与IEnumerable<T>相关的对象,我会更熟悉这种方法,这样你就可以依赖LINQ的惰性,但在这种情况下它并没有因为你正在做计数。我建议使用某种形式的Select来限制被查询的字段,但在后两种情况下,它们无论如何都会提取所有结果,因此它可能无法获得2/3的可能情况。如果您发现查询通常由UserName完成,则可能值得添加。