2013-02-05 92 views
1

我從數據庫中提取一些數據,通過這條線之下:搜索<T>

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

我想SEACH在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; 
} 

是否有任何簡單或實用的方法來搜索IQueryable接口通過使用LINQ或其他東西?

回答

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

你可以不喜歡它

bool isSuperUser = UserList.Any(a=>a.type==a.SuperUser) 
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; 
} 
0
UserList .Where(user => user.Type== (int)UserType.SuperUser);