Home > OS >  FirstOrDefault LINQ query with condition
FirstOrDefault LINQ query with condition

Time:08-03

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.

CodePudding user response:

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();

CodePudding user response:

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

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

CodePudding user response:

This can be simplified further as:

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