在IQueryable中搜索<;T>;
本文关键字:gt IQueryable lt 搜索 | 更新日期: 2023-09-27 17:57:36
我正在通过下面的行从数据库中提取一些数据:
IQueryable<user> UserList = DatabaseContext.Users.GetAll();
我想在用户列表中查找一些内容,例如:
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接口中搜索?
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;
}
你可以像一样完成
bool isSuperUser = UserList.Any(a=>a.type==a.SuperUser)
要搜索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;
}
UserList .Where(user => user.Type== (int)UserType.SuperUser);