1

我通过下面的这一行从数据库中提取一些数据:

IQueryable<user> UserList = DatabaseContext.Users.GetAll();

我想在 UserList 中搜索一些东西,例如:

foreach (var User in UserList)
{
    if (User.type == (int)UserType.SuperUser)
    {
        IsRecordFound = true;
        break;
    }
}

然后我根据国旗的状态做一些事情:

if (!IsRecordFound)
{
    AesCrypto aesCrypto = new AesCrypto();
    user newuser = new user();
    newuser.username = DEFAULT_SUPER_USER_NAME;
    newuser.password = aesCrypto.Encrypt(DEFAULT_SUPER_USER_PASSWORD);
    newuser.type = (int)UserType.SuperUser;
    newuser.create_date = DateTime.Now;
    newuser.last_login = newuser.create_date;
    newuser.email_address = DEFAULT_SUPER_USER_EMAIL_ADDR;
    newuser.login_count = 1;

    DatabaseContext.Users.Add(newuser);
    if (!DatabaseContext.Save())
        return false;
}

是否有任何简单或实用的方法可以通过使用 LINQ 或其他方式在 IQueryable 接口中进行搜索?

4

4 回答 4

3
if (!UserList.Any(x => x.Type == (int)UserType.SuperUser))
{
    AesCrypto aesCrypto = new AesCrypto();
    user newuser = new user();
    newuser.username = DEFAULT_SUPER_USER_NAME;
    newuser.password = aesCrypto.Encrypt(DEFAULT_SUPER_USER_PASSWORD);
    newuser.type = (int)UserType.SuperUser;
    newuser.create_date = DateTime.Now;
    newuser.last_login = newuser.create_date;
    newuser.email_address = DEFAULT_SUPER_USER_EMAIL_ADDR;
    newuser.login_count = 1;

    DatabaseContext.Users.Add(newuser);
    if (!DatabaseContext.Save())
        return false;
}
于 2013-02-05T10:49:36.593 回答
0

你可以这样做

bool isSuperUser =  UserList.Any(a=>a.type==a.SuperUser)
于 2013-02-05T10:49:41.483 回答
0

要搜索 IQueryable,请使用where

var foundUsers = UserList.Where( usr => usr.Type == (int)UserTypes.SuperUser );

if( foundUsers == null && foundUsers.Count() == 0 ) // only one of these is required.. I forget which though :s
{
    AesCrypto aesCrypto = new AesCrypto();
    user newuser = new user();
    newuser.username = DEFAULT_SUPER_USER_NAME;
    newuser.password = aesCrypto.Encrypt(DEFAULT_SUPER_USER_PASSWORD);
    newuser.type = (int)UserType.SuperUser;
    newuser.create_date = DateTime.Now;
    newuser.last_login = newuser.create_date;
    newuser.email_address = DEFAULT_SUPER_USER_EMAIL_ADDR;
    newuser.login_count = 1;

    DatabaseContext.Users.Add(newuser);
    if (!DatabaseContext.Save())
        return false;
}
于 2013-02-05T10:52:46.153 回答
0
UserList .Where(user => user.Type== (int)UserType.SuperUser);
于 2013-02-05T10:53:14.730 回答