Initialize var to null - c#

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?

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 nullby 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;
}

Related

c# Linq expression builder Expression.Equal showing parms around the wrong way

I am trying to build some dynamic Linq using expressions for an advance search facility.
I call my define expression builder like so:
IQueryable<DocPod> retval = Enumerable.Empty<Doc>().AsQueryable();
retval = DefineSearchExpression(x => x.Id,
searchCriteria.searchData.Comparison,
searchCriteria.searchData.NumberFrom,
searchCriteria.searchData.NumberTo);
To explain the above, I have multiple properties on a page where each property has a drop down providing various search types, so in the case above I have an int called Id, then a comparison which can be things like equals, not equals, greater than, etc... Then depending on the selected comparison, NumberFrom is the main search parameter and should always be populated, but in the case of between comparison, the NumberTo parameter is also populated.
The function DefineSearchExpression, is shown below:
private IQueryable<Docs> DefineSearchExpression(Expression<Func<Docs, object>> searchColumnName, int compare, object minValue, object maxValue)
{
IQueryable<Docs> retval = Entities.Docs.AsQueryable();
// We must have a minValue to process
if (minValue == null)
{
return retval;
}
// LINQ Expression that represents the column passed in searchColumn
var columnExpression = GetMemberExpression(searchColumnName);
// LINQ Expression to represent the parameter of the lambda you pass in
ParameterExpression parameterExpression = (ParameterExpression)columnExpression.Expression;
// Expressions to represent min and max values
Expression minValueExpression = null;
Expression maxValueExpression = null;
Expression minComparisonExpression = null;
Expression maxComparisonExpression = null;
// Represents the completed filter
Expression<Func<Docs, bool>> filterLambdaExpression = null;
// setup vars
if (minValue.IsNumeric())
{
var intfromValue = int.Parse(minValue.ToString());
minValueExpression = Expression.Constant(intfromValue);
if (maxValue != null)
{
var inttoValue = int.Parse(maxValue.ToString());
maxValueExpression = Expression.Constant(inttoValue);
}
}
else if (minValue.IsDate())
{
var dtfromValue = DateTime.Parse(minValue.ToString());
minValueExpression = Expression.Constant(dtfromValue);
if (maxValue != null)
{
var dttoValue = DateTime.Parse(maxValue.ToString());
maxValueExpression = Expression.Constant(dttoValue);
}
}
// Expression represented by selection in dropdown List
switch (compare)
{
//
// THIS IS WHERE THE FIRST ISSUES IS LOCATED
//
//
case 0: // This should be equivalent to: field = value
minComparisonExpression = Expression.Equal(minValueExpression, columnExpression);
filterLambdaExpression = Expression.Lambda<Func<Docs, bool>>(minComparisonExpression, parameterExpression);
break;
}
retval = retval.AsQueryable().Where(filterLambdaExpression);
return retval.AsQueryable();
}
As you can see, I am trying to take into account numeric, datetime and finally string data for searching.
When the above code is executed, when the code within the switch Case 0 provides the following anomaly.
minComparisonExpression has the debug value of 1977836648 == $x.Id
I have tried to swap these values around, but with little success, if anyone knows how to fix this, I would be very grateful.
Secondly, when DefineSearchExpression returns, the new expression is lost, this is most probably me, but I just cannot see it.
Oops. Thank you for spotting the error, but that does not help as the offending code is in the Switch Case 0 statements, the date code is not run at all at the moment.
Code updated!

Check if non-valued query string exists in url with C#

I've seen a couple examples of how to check if a query string exists in a url with C#:
www.site.com/index?query=yes
if(Request.QueryString["query"]=="yes")
But how would I check a string without a parameter? I just need to see if it exists.
www.site.com/index?query
if(Request.QueryString["query"] != null) //why is this always null?
I know there's probably a simple answer and I'll feel dumb, but I haven't been able to find it yet. Thanks!
If you do not specify a value, the key will be automatically set to null, so you cannot check its existence.
In order to check if the value actually exists, you can check in the collection of Values equalling null if it contains your Key:
Request.QueryString.GetValues(null).Contains("query")
this is the fastest way to check it thanks to Ludovic's answer
if(Request.QueryString.GetValues(null)?.Contains("query")??false)
It returns null because in that query string it has no value for that key. I think the check you're looking for is this:
if(Request.QueryString.Keys.OfType<string>().Any(k => k == "query"))
or even:
if(Request.QueryString.AllKeys.Any(k => k == "query"))
The latter is probably more appropriate because that array is already cached.
If query was included as a parameter, but no value was specified, then the value of query will be null but it will still exist in Request.QueryString.AllKeys.
If query was not included, it won't exist in Request.QueryString.AllKeys at all.
Ludovic has the right answer. But I would like to offer a more robust version.
var valueEntries = Request.QueryString.GetValues((string)null) ?? new string[] {};
if (valueEntries.Contains("query", StringComparer.OrdinalIgnoreCase))
{
// value is specify in querystring
}
else
{
// value is NOT specify in querystring
}
This is verbose and it works. Here is a .NET Fiddle.
#using System.Linq;
#{
var empties = Request.Url.Query
.Split('&')
.Where(s => !s.Contains("=") || s.Last() == '=');
var keyExistsAndIsEmpty = empties.Any(x => x.Contains("target-key")
}
It turns out that if the value is null, then the key is also null in the QueryString collection. Your best bet is simply to assign a value to the query. There might be a way for you to rename the parameter so that this makes more semantic sense. For example instead of www.site.com/index?getdocument=yes you could do www.site.com/index?action=getdocument
However if you still want the url www.site.com/index?query to work, there is a way: don't use the QueryString at all and parse the URL manually:
string query = Request.RawUrl.Split('?')[1];
if (query == "query")
{
// send the data
}
You cannot use a null check to determine if a key exists when the "=" is not supplied since null means that the key wasn't in the query string.
The problem is that "query" is being treated as a value with a null key and not as a key with a null value.
In this case the key is also null inside Request.QueryString.AllKeys.
I used this generic method to "fix" the null key problem in the query string before using it. This doesn't involve manually parsing the string.
Usage example:
var fixedQueryString = GetFixedQueryString(Request.QueryString);
if (fixedQueryString.AllKeys.Contains("query"))
{
}
The method:
public static NameValueCollection GetFixedQueryString(NameValueCollection originalQueryString)
{
var fixedQueryString = new NameValueCollection();
for (var i = 0; i < originalQueryString.AllKeys.Length; i++)
{
var keyName = originalQueryString.AllKeys[i];
if (keyName != null)
{
fixedQueryString.Add(keyName, originalQueryString[keyName]);
}
else
{
foreach (var keyWithoutValue in originalQueryString[i].Split(','))
{
fixedQueryString.Add(keyWithoutValue, null);
}
}
}
return fixedQueryString;
}
I Prefer to use:
If(Request.QueryString.AllKeys.Contains("query")
{
//
}

How to Assign a Query Result to an Integer Array

public List<Workflow> GetMyWorkflows(int[] MyRoles)
{
int[] myWorkflowIDs = new int[] { };
RapidWorkflowDataContext context = new RapidWorkflowDataContext();
var query = from w in context.WorkflowRoles
where MyRoles.Contains((int)w.RoleID)
select w.WorkflowID;
var distinctWorkflows = query.Distinct();
myWorkflowIDs = distinctWorkflows.toArray();
return myWorkflowIDs;
}
In this method I want to retrieve an array of workflows that a user can
access.
I get the following error : Cannot implicitly convert type 'int?[]' to 'int[]'
I want to retrieve an array of workflows
But your method must return a List<Workflow> or a List<int>.
So you should skip the array idea. The other issue is between int and int?. You can solve that in the select clause with select w.WorkflowID.Value or select w.WorkflowID ?? 0. Or simply select w for a List<Workflow>.
Also it is a good idea to dispose a context when it becomes unreachable.
public List<int> GetMyWorkflows(int[] MyRoles)
{
using (RapidWorkflowDataContext context = new RapidWorkflowDataContext())
{
var query = from w in context.WorkflowRoles
where MyRoles.Contains((int)w.RoleID)
select w.WorkflowID ?? 0;
// select w; to return a List<WorkFlow>
var distinctWorkflows = query.Distinct();
return distinctWorkflows.ToList(); // ToList because we are closing the Context
}
}
I'm going to guess that WorkflowID is of type int?. If you are certain that it cannot be null, change your central query to:
var query = from w in context.WorkflowRoles
where MyRoles.Contains((int)w.RoleID)
select w.WorkflowID.Value;
This will ensure that query is now of type IEnumerable<int> instead of IEnumerable<int?>, with the int following on throuhh the Distinct() and ToArray() functions.
This seems like a pretty good error to me
Cannot convert type 'int?[]' to 'int[]'
You must have an array of type int? and be trying to implicitly convert it to int.
Therefore you have two options - stop trying to implicitly convert, and allow the result to be int?[], like this:
int?[] myWorkflowIDs = new int?[] { };
or force the convert to take place, like this:
RapidWorkflowDataContext context = new RapidWorkflowDataContext();
var query = from w in context.WorkflowRoles
where MyRoles.Contains((int)w.RoleID)
select (int)w.WorkflowID;
// or w.WorkflowID ?? 0; as necessary
So int? can also be written Nullable<int> which is basically an int that can take null values. For example:
int? nullableNumber = 5; // Set to a value
nullableNumber = null? // Set to null (which is possible because int? is nullable).
As you can imagine, Nullable<int> is useful for databases because sometimes you might have a column that has null values, and so this type gives a useful means of mapping to this sort of value. The problem, though is that in your code you have to deal with two different types, int vs. int?. You can cast between the two values by using:
// If the nullable-integer is not-null then use it's value, else default to `0`.
int nonNullable = nullableNumber ?? 0;
which will replace nulls with 0 if the value is null. Or you can just store your myWorkflowIDs in a nullable value (Nullable<int>[] or int?[]), which semantically better reflects what the column value in the database actually is.

Entity framework with Linq

I have following method. I need to return var tynames by method so what would be the return type of the method will it be List<string> or something else and also what is the use of FirstOrDefault().
Thanks in advance for your reply
public static List<string> AppType()
{
var context = new Dll_IssueTracking.IssuTrackingEntities();// Object context defined in Dll_IssuTracking DLL
var query = from c in context.ApplicationTypes//Query to find TypeNames
select new { c.TypeName };
var **TypeNames** = query.FirstOrDefault();
}
FirstOrDefault returns the first element found, or the default value (which is null in this case) if the query returned no results.
In this case the return value of the method should be ApplicationType:
public static ApplicationType AppType()
{
var context = new Dll_IssueTracking.IssuTrackingEntities(); // Object context defined in Dll_IssuTracking DLL
var query = from c in context.ApplicationTypes //Query to find TypeNames
select new { c.TypeName };
return query.FirstOrDefault();
}
FirstOrDefault return first element in sequence, in this sample ApplicationTypes is your sequence or a default value if the sequence contains no elements.
FirstOrDefault is an extension method which looks something like this:
public T FirstOrDefault>T>(this IEnumerable<T> query)
{
return query.Any() ? query.First() : default(T);
}
So, it returns the first element in the sequence if it is not empty, or the default of the type if the sequence is empty.
For Instance, if you have an Enumerable<LinqEntity>, then most likely default(LinqEntity) is null. If you had something like Enumerable<int> then default(int) is 0.

How to check a var for null value?

I am using PetaPoco Micro-ORM with C# 4.0.
The code below retrieves a single row from the database:
var result = db.SingleOrDefault<TdUsers>(getUserQuery);
I would like to check whether or not the result contains any rows, and whether is null. What is the best way to do this?
if (result == null || result.Count() == 0) {
// Checks whether the entire result is null OR
// contains no resulting records.
}
I think the problem is not in your check for null, because linq is lazy loading. Your error is in using the expression db.SingleOrDefault<TdUsers>(getUserQuery);.
.Single<T>(expression) does not return null - it errors if the result returns no values.
.SingleOrDefault<T>(expression), however, returns a null value if the expression results in no values - and therefore is best combined with an if (result == null) type check, as you're using here.
var result = db.SingleOrDefault<TdUsers>(getUserQuery);
In above code SingleOrDefault will return null vale or the specified
generic type(it's known on runtime).
Inorder to check whether the returned values is null or not you can simply use
if(result!=null)
{
//do your code stuff
}
else
{
//stuff do be done in case where result==null
}
You could do:
result.ToList() // Convert result to a list
if (result.Any()) {
// result is not null
}
var v = result.ToList();
now check
if (v is not null)
{
}
else if (v.Count()>0)
{
}

Categories