简体   繁体   中英

FirstOrDefault LINQ query with condition

I am new to the linq queries and wants to use FirstOrDefault in my existing LINQ query.

List<vUserAll> employee = (from o in db.vUsersAll
  where (o.sAMAccountName == modifiedAccountName || o.CN == modifiedAccountName) && o.Domain == "dExample"  
  select o).ToList();

What's the correct way to do this?

Thanks.

If above mentioned is the case, then you can use a labmda as following

var firstOrDefaultResult = db.vUsersAll.Where(o=> 
(o.sAMAccountName == modifiedAccountName || o.CN == modifiedAccountName) 
&& o.Domain == "dExample").FirstOrDefault() 

If you want to use same above expression then,

vUserAll employee = (from o in db.vUsersAll
  where (o.sAMAccountName == modifiedAccountName || o.CN == modifiedAccountName) && o.Domain == "dExample"  
  select o).FirstOrDefaul();

It's a lot easier if you only use linq extensions. Eg

var filtered = all users.Where(u => u. Field == filter).FirstOrDefault();

This can be simplified further as:

var filtered = db.vUsersAll.FirstOrDefault(u => u. Field == filter);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM