Reputation: 12369
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
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
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
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
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
Reputation: 7855
return (null == DataContext.Employee.Where(e=>e.id==id).FirstorDefault());
Upvotes: 3