Reputation: 44285
I have seen how to initialize var to null. This does not help in my situation. I have
string nuller = null;
var firstModel = nuller;
if(contextSelectResult.Count() > 0)
firstModel = contextSelectResult.First();
I get error
Cannot implicitly convert type 'SomeNamespace.Model.tableName' to 'string'.
I am trying to avoid try/catching InvalidOperation
for First()
when no first exists as its expensive. So, how can I get past the scope issue here?
Upvotes: 8
Views: 38277
Reputation: 21
Please Try this option:
var var_name = (dynamic)null;
or
var var_name = (Type*)null;
Type* : eg --> string, var, int
Upvotes: 2
Reputation: 545
You can use the generic for this case also
public static dynamic GetTheListOfDevicesDependOnDB(int projectID)
{
List<Devices_Settings> ListDevices_Settings = new List<Devices_Settings>();
var db = new First_DataContext();
var devices = (dynamic) null;
switch (projectID)
{
case (int)enmProjectType.First:
db = new First_DataContext();
devices = db.Device_Fisrt.ToList();
break;
case (int)enmProjectType.Second:
var db1 = new Second_DataContext();
devices = db1.Device_Second.ToList();
break;
default:
break;
}
foreach (var item in devices)
{
//TODO
}
return ListDevices_Settings;
}
Upvotes: 0
Reputation: 41685
If there is no First it'll be a null for reference types:
var firstModel = contextSelectResult.FirstOrDefault();
Upvotes: 1
Reputation: 51644
Try FirstOrDefault
instead. It returns null
by default if there is no item.
Upvotes: 2
Reputation: 1501656
Simply use FirstOrDefault()
instead. The whole point of FirstOrDefault
is to return the first element of the sequence if it exists, or the default value of the element type (i.e. null for all reference types) otherwise.
Note that in other cases where you wish to check for the existence of any elements, using Any()
can sometimes be more efficient than Count() > 0
- it depends on the exact context, but IMO it's a simpler way of expressing what you're looking for anyway.
Upvotes: 6
Reputation: 108957
You can use FirstOrDefault()
instead.
firstModel = contextSelectResult.FirstOrDefault();
if(firstModel != null)
{
...
}
Upvotes: 7