skip to Main Content

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?

3

Answers


  1. 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();
    
    Login or Signup to reply.
  2. It’s a lot easier if you only use LINQ extensions. For example,

    var filtered = all users.Where(u => u. Field == filter).FirstOrDefault();
    
    Login or Signup to reply.
  3. This can be simplified further as:

    var filtered = db.vUsersAll.FirstOrDefault(u => u. Field == filter);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search