Home > Back-end >  FirstOrDefault LINQ query with a condition
FirstOrDefault LINQ query with a condition

Time:08-16

I am new to LINQ queries and want 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?

CodePudding user response:

This can be simplified further as:

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

CodePudding user response:

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

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

If you want to use the 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. For example,

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