Vishal
Vishal

Reputation: 12369

How to write boolean function in a single line in C#?

public bool IsNewUser(int id)
{
  var data= DataContext.Employee.Where(e=>e.id==id).FirstorDefault();
  if(data==null)
     return true;
  return false;
}

How can I write the above function logic using maybe ?? or something else in a single line in C#? I am sure that must be possible just can't think right now..Thanks

Upvotes: 1

Views: 3453

Answers (8)

Ian Henry
Ian Henry

Reputation: 22403

return DataContext.Employee.Where(e=>e.id==id).FirstorDefault() == null;

?? is the null coalescing operator, used to assign a default value instead of null. IE

data = data ?? GetNonNullData();

?: is the ternary conditional, probably what you were thinking of. But it's not actually necessary in this case.

Upvotes: 3

hunter
hunter

Reputation: 63522

This wouldn't be a case to use ?? but this should help:

public bool IsNewUser(int id)
{
    return !DataContext.Employee.Any(e => e.id == id);
}

?? would be used doing something like this:

public Employee GetEmployeeOrNew(int id)
{
    return DataContext.Employee.Where(e => e.id == id).FirstorDefault() ?? new Employee();
}

Upvotes: 5

Marc Gravell
Marc Gravell

Reputation: 1062770

return DataContext.Employee.Any(e => e.id == id);

Upvotes: 0

Ian Nelson
Ian Nelson

Reputation: 58753

The Any operator would be more appropriate than FirstOrDefault:

public bool IsNewUser(int id)
{
   return !DataContext.Employee.Any(e => e.id == id);
}

Upvotes: 3

Ian Mercer
Ian Mercer

Reputation: 39277

return !DataContext.Employee.Any(e=>e.id==id);

Upvotes: 2

Femaref
Femaref

Reputation: 61437

You should use the Any method instead of the Where...FirstOrDefault construct:

public bool IsNewUser(int id)
{
  return !DataContext.Employee.Any(e=>e.id==id);
}

Upvotes: 2

VoodooChild
VoodooChild

Reputation: 9784

return data == null ? true : false;

Upvotes: 0

echo
echo

Reputation: 7855

return (null == DataContext.Employee.Where(e=>e.id==id).FirstorDefault());

Upvotes: 3

Related Questions