Initialize var to null
I have seen how to initialize var to null. This does not help in my situat开发者_JAVA技巧ion. 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?
You can try this:
var firstModel=(dynamic) null;
You can use FirstOrDefault()
instead.
firstModel = contextSelectResult.FirstOrDefault();
if(firstModel != null)
{
...
}
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.
Try FirstOrDefault
instead. It returns null
by default if there is no item.
Please Try this option:
var var_name = (dynamic)null;
or
var var_name = (Type*)null;
Type* : eg --> string, var, int
If there is no First it'll be a null for reference types:
var firstModel = contextSelectResult.FirstOrDefault();
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;
}
精彩评论