Linq and anonymous type - c#

select new
{
Selected = (cvf != null && cvf.Deleted==false)
}
The above statement proceeds to check cvf.Deleted even if cvf is null. Then it throws an invalid object reference error.
How do I fix this?

Probably something else going on since && will short-circuit evaluate. That said, try this instead:
select new
{
Selected = cvf != null
? !cvf.Deleted
: false
};

Related

Linq query return coumn value null handle

In the datatable return one column list, in this scenario table return null value, I want to handle null values
DataTable PreviousQuarter = GroupFive.Tables["PreviousQuarter_108_49_100_51"];
LastQuarter.Merge(PreviousQuarter);
var AHCT = (from ah in PreviousQuarter.AsEnumerable()
where ah.Field<int>("ParameterID") == 10
|| ah.Field<int>("ParameterID") == 11
|| ah.Field<int>("ParameterID") == 12
|| ah.Field<int>("ParameterID") == 13
select ah.Field<int>("Tot_Tkts_Closed")).ToList();
if (AHCT == null)
{
Response = "";
}
It will come null , I am getting error Specified cast is not valid .
how to handle this error.
Your are selecting a value which is not available in table and before getting the result you type cast it into int.
That's why it throws error.
Its better to select first and then convert it into int.
I think #madreflection gave you the answer in the comments.
Since you're getting this error:
Specified cast is not valid
my guess is that you have a null value in the Tot_Tkts_Closed column. In that case, cast to nullable int int? instead. Update this line:
select ah.Field<int?>("Tot_Tkts_Closed")
The other possibility is ParameterID is null, in which case a similar change should resolve it: ah.Field<int?>("ParameterID").
Rather than checking if the list is null you could check to see if its empty. In that case, use the Count property:
if (AHCT.Count == 0)
{
Response = "";
}

ExecuteScalar null value error

This is my code..
object o = DBExecuteScalar(myQuery);
if ((int.parse(o.ToString())) <= 2 || (o is null))
{
// my task....
}
In this code, 'o is null' part is giving error. Any help how to deal with these both conditions in single if statement.. What I want is that the value of o should be (null,0,1,2).
Any help ??
In C#, the is operator checks for type equality. You need to check for null as o == null:
object o = DBExecuteScalar(myQuery);
if ((o == null) || (int.parse(o.ToString())) <= 2)
{
// my task....
}
You also need to check for null before you try to perform any actions on it
when you reverse the conditions in the if, then it should work.
In your case the ToString is called first on object o. But because o is null this will result in an exception.
When you reverse the order of your conditions, then the nullcheck will be first. The second part of the or (||) is only evaluated when the first part is false. This will prevent the exception from occurring
With || operator first condition is evaluated first - you want to check if is null first.
Also the int.Parse is not necessary. As RGraham mentioned is null is not a proper way how to check for null.
if (o == null || o == DBNull.Value || (int)o <= 2)

Better Way to Check for Null Value in Linq Path

Here is an example of an assignment to a linq path pulled from code first...
applicants = appRegistrations
.ToList()
.Select(c => new ApplicantList() {
PartnerType = c.Participant != null ? c.Participant.PartnerType != null ? c.Participant.PartnerType.PartnerTypeName : "" : ""
});
Notice the null checks - is there a more elegant way I can write this code considering Participant AND PartnerType could be null?
I just hate checking for nulls on each property.
You could check if one of both are null:
List<ApplicantList> applicants = appRegistrations
.Select(ar => c.Participant == null || c.Participant.PartnerType == null
? "" : c.Participant.PartnerType.PartnerTypeName)
.Select(str => new ApplicantList { PartnerType = str })
.ToList();
You can shorten it a little bit:
PartnerType = c.Participant != null && c.Participant.PartnerType != null
? c.Participant.PartnerType.PartnerTypeName
: ""
When you construct the objects such as Participant, make sure that the properties are never null. Think if null is a valid value for a Participant? If not then you should never allow it to be null. Take a constructor parameter and add a guard clause to check for nulls. Otherwise initialize them to a default value.
Also, see NULL Reference Pattern.

Left outer join , Object reference not set to an instance of an object

I am trying to perform left outer join on 2 objects and getting an error : Object reference not set to an instance of an object.
The objects look like that
var deliverables = OCHART.GetACAPValues(organization, ReportingPeriod, FiscalYear, "(09-10.10a) Outreach Significant").ToList();
var references = (from rf in OCHART.References where rf.RefType.Equals("09-10.10a") && rf.Comments.Equals("2") select rf).ToList();
In which deliverables might often return 0 records. Unfortunately I cannot just go and join two tables from database so deliverables must be an object.
Can somebody please point me in the right direction
Thanks,
My code is
var items = (from rf in references
join pt in deliverables on rf.Description equals pt.b into prt
from x in prt.Where(prt2 => prt2.a.Equals(audience)).DefaultIfEmpty()
where rf.RefType.Equals("09-10.10a") && rf.Comments.Equals("2")
select new
{
audience = (string)(audience == null ? "" : audience),
RefType = (string)(rf.RefType == null ? "" : rf.RefType),
RefOrder = (int)(rf.RefOrder == null ? 0 : rf.RefOrder),
refName = (string)(rf.Description == null ? "" : rf.Description),
collumn_attr = (string)(x.b == null ? string.Empty : x.b),
value = (int)(x.ACAP == null ? (int?)null : x.ACAP)
})
.OrderBy(o => o.RefOrder)
.Take(9)
.ToList();
EDIT:
After some more debuging it appears that I get error on following lines in my code
collumn_attr = (string)(x.b == null ? string.Empty : x.b),
value = (int)(x.ACAP == null ? (int?)null : x.ACAP)
I noticed even when I have values (added for testing) in deliverables and when values are matching the query will execute properly, but when there is no match in deliverable that's when I get the error message.
The issue is probably with handling the null values.
I think x is null and is causing a NullReferenceException in the following lines:
collumn_attr = (string)(x.b == null ? string.Empty : x.b),
value = (int)(x.ACAP == null ? (int?)null : x.ACAP)
This judgment is based on the from x in line's DefaultIfEmpty() call, typical of left-outer-joins.
In database code, you would write something like x.ACAP == null to detect the case where there was no matching join element. If you change this replace the 'x.property == null' checks with "x == null" checks, I suspect your problem will clear up.
There's still the problem with the second line - you're going to get an exception at run-time if you try to cast the value (int?)null to an integer. Using a meaningful default int value such as 0 in the case that x == null will clear that up.
If you step through your code, before the query is executed do you actually see "deliverables" and "references" being populated with data ?
Investigate all child tables/properties you're using in your query. The reason you're getting that error is most likely because one of the properties you're using while comparing is null.
.RefType .Comment for example.
Maybe .RefType is null and it's having problems sorting at the end. Difficult to say without seeing what's in those two collections.
Added after your comment:
Note that it's better not to use .Equals() when your variable could be null. Use == instead. Reference: http://www.dotnetperls.com/string-equals
Also imagine that (x.ACAP == null ? (int?)null : x.ACAP) returns a null.
You're casting that whole thing as an int : value = (int)(x.ACAP == null ? (int?)null : x.ACAP). Casting null as n int will obviously fail
Just for the record, the new Null-conditional operators in C# 6.0 could be used like this:
collumn_attr = x?.b ?? string.Empty,
value = x?.ACAP

Where statement in a Linq request

I try to execute this Linq request :
var lqClassResult = from classItem in this.dataSet._class.AsEnumerable()
join namespaceItem in this.dataSet._namespace.AsEnumerable()
on classItem.Field<int>("namespace_id") equals namespaceItem.Field<int>("id")
where classItem.Field<string>("class_name").ToLowerInvariant().Contains(className.ToLowerInvariant()) &&
namespaceItem.Field<string("namespace_name").ToLowerInvariant().Contains(namespaceName.ToLowerInvariant())
orderby namespaceItem.Field<string>("namespace_name"),classItem.Field<string>("class_name")
select new {
class_name = classItem.Field<string>("class_name"),
namespace_name = namespaceItem.Field<string>("namespace_name")
};
But when i execute it, Visual Studio Throw a NullReferenceException because of this line :
namespaceItem.Field("namespace_name").ToLowerInvariant().Contains(namespaceName.ToLowerInvariant())
in where clause.
If anyone can help me it would be great
Try
on classItem.Field<int>("namespace_id") equals namespaceItem.Field<int>("id")
let namespaceName = namespaceItem.Field<string("namespace_name")
where classItem.Field<string>("class_name").ToLowerInvariant().Contains(className.ToLowerInvariant()) && namespace != null &&
namespace.ToLowerInvariant().Contains(namespaceName.ToLowerInvariant())
I would guess that namespaceItem.Field("namespace_name") is returning null.
Is this a valid return value for that method? If not, then check your underlying code.
If this is a valid return value then you need to check for a null before calling ToLowerInvariant():
var lqClassResult = from classItem in this.dataSet._class.AsEnumerable()
join namespaceItem in this.dataSet._namespace.AsEnumerable()
on classItem.Field<int>("namespace_id") equals namespaceItem.Field<int>("id")
where classItem.Field<string>("class_name").ToLowerInvariant().Contains(className.ToLowerInvariant()) &&
namespaceItem.Field<string("namespace_name") ! = null &&
namespaceItem.Field<string("namespace_name").ToLowerInvariant().Contains(namespaceName.ToLowerInvariant())
orderby namespaceItem.Field<string>("namespace_name"),classItem.Field<string>("class_name")
select new {
class_name = classItem.Field<string>("class_name"),
namespace_name = namespaceItem.Field<string>("namespace_name")
};
Note the extra null check:
namespaceItem.Field<string("namespace_name") ! = null &&
However, this is only a guess: you need to determine where the null value is coming from.
2 possibilities:
There is no field
Field("namespace_name")
returns null because there is no field-
There isa field, but
Field("namespace_name").ToLowerInvariant().
returns null because the VALUE in namespace_name is a null so ToLowerInvariant also returns null, which will blow the contains.

Categories

Resources