How to handle NULL when using String.StartsWith method - c#

How do I handle a null when using the String.StartsWith() in a complex where clause ?
var value = _context.Repo.Pages.Where(r => r.Sdate <= data.Pdate && (r.Edata == null || data.RData <= r.Edata)
&& ......
&& ...... several conditions
&& ......
|| (data.SisPlan.StartsWith("T") && r.SisN == data.SisCal));
I've tried data?.SisPlan.StartsWith("T") but get the message:
Operator '&&' cannot be applied to opperands of type 'bool?' and
'bool'
I'm trying to prevent doing a null check outside of the where clause.

The usual way is to write:
|| ((data?.SisPlan?.StartsWith("T") ?? false) && r.SisN == data.SisCal));
We rely on the ?? operator to get the null case and in this case we return a false value. The ?? is called the null coalescing operator.
Basically,
var a = data?.SisPlan?.StartsWith('T') ?? false;
is a syntaxic sugar for
bool a = false;
if (data != null && data.SisPlan != null && data.SisPlan.StartsWith('T'))
a = true;

Related

convert lambda expression to function

I wish to debug lambda expression but its not possible as it sets breakpoint on whole expression.
Here is my lambda expression
public bool CanRevert => _objectEntity != null && !(_objectEntity != null &&
ObjectDescription == _objectEntity.DTO.Description &&
ObjectInstance == _objectEntity.DTO.ObjectInstance.ToString() &&
Name == _objectEntity.DTO.ObjectName &&
(SelectedDevice != null && SelectedDevice.Id == _objectEntity.DTO.DeviceID) &&
(_objectEntity.DTO.ObjectCategoryID.HasValue ? (SelectedObjectCategory != null && SelectedObjectCategory.Id == _objectEntity.DTO.ObjectCategoryID.Value) : SelectedObjectCategory == null) &&
(_objectEntity.DTO.ObjectTypeID.HasValue ? (SelectedObjectType != null && SelectedObjectType.Id == _objectEntity.DTO.ObjectTypeID.Value) : SelectedObjectType == null));
I wanted to put breakpoint inside selectedDevice but i cant. Hence i tried to write it like
public bool CanRevert()
{
if (SelectedDevice != null)
{
var s = SelectedDevice.Id == _objectEntity.DTO.DeviceID;
}
var d = _objectEntity != null && !(_objectEntity != null &&
ObjectDescription == _objectEntity.DTO.Description &&
ObjectInstance == _objectEntity.DTO.ObjectInstance.ToString() &&
Name == _objectEntity.DTO.ObjectName &&
(SelectedDevice != null && SelectedDevice.Id == _objectEntity.DTO.DeviceID) &&
(_objectEntity.DTO.ObjectCategoryID.HasValue ? (SelectedObjectCategory != null && SelectedObjectCategory.Id == _objectEntity.DTO.ObjectCategoryID.Value) : SelectedObjectCategory == null) &&
(_objectEntity.DTO.ObjectTypeID.HasValue ? (SelectedObjectType != null && SelectedObjectType.Id == _objectEntity.DTO.ObjectTypeID.Value) : SelectedObjectType == null));
return d;
}
Is it right way to convert it? I ask because i am starting to get somewhere in application that Binding to this method is not supported
You can achieve the same result like this.
Put a breakpoint in your expression.
Start Debugging (F5)
Highlight (SelectedDevice != null && SelectedDevice.Id == _objectEntity.DTO.DeviceID) in your expression
Right-click and select Add Watch
Now you have its calculated value in the Watch window. (Usually pops up at the bottom)
You can use Quick Watch (Shift+F9) if you want its value once.

How can I pull a repeated where clause expression from linq into a function?

I have a large project where I have dozens of linq statements where I am looking for a matching record by checking several fields to see if they match or both field and compared field are null.
var testRecord = new { firstField = "bob", secondField = (string)null, thirdField = "ross" };
var matchRecord = dataContext.RecordsTable.FirstOrDefault(vi =>
(vi.first == testRecord.firstField || ((vi.first == null || vi.first == string.Empty) && testRecord.firstField == null))
&& (vi.second == testRecord.secondField || ((vi.second == null || vi.second == string.Empty) && testRecord.secondField == null))
&& (vi.third == testRecord.thirdField || ((vi.third == null || vi.third == string.Empty) && testRecord.thirdField == null)));
//do stuff with matchRecord
Ideally I would replace all that duplicated code (used around 50 times across the system I'm working on) with something like the following
Expression<Func<string, string, bool>> MatchesOrBothNull = (infoItem, matchItem) => (
infoItem == matchItem || ((infoItem == null || infoItem == string.Empty) && matchItem == null));
var matchRecord = dataContext.RecordsTable.FirstOrDefault(vi =>
MatchesOrBothNull(vi.first, testRecord.firstField)
&& MatchesOrBothNull(vi.second, testRecord.secondField)
&& MatchesOrBothNull(vi.third, testRecord.thirdField));
//do stuff with matchRecord
My question is two-fold: First, is there a matched or both null function already available? (I've looked without luck).
Second, the code block above compiles, but throws a "no supported translation to sql" error, is there a way to have a function in the where clause? I know that there is a translation because it works if I don't pull it into the function. How can I get that translated?
First of all you can check whether string is null or empty with single code which is called : String.IsNullOrEmpty(vi.first). You need a method like this one :
public bool MatchesOrBothNull(string first,string second){
if(first==second||String.IsNullOrEmpty(first)||String.IsNullOrEmpty(second))
return true;
else return false;
}
You can use it in where clause
var matchRecord = dataContext.RecordsTable.Where(vi =>
MatchesOrBothNull(vi.first, testRecord.firstField)
&& MatchesOrBothNull(vi.second, testRecord.secondField)
&& MatchesOrBothNull(vi.third, testRecord.thirdField)
).FirstOrDefault();

C# short-circuiting weirdness

Given a = null
Shouldn't this not throw an exception?
if(a != null && ((string)a).ToLower()=="boo"){
... operation
}
Due to lazy evaluation the second statement should never be called so this ((string)a).ToLower() shouldn't be throwing an exception right ?
UPDATE
IOrderedEnumerable<SPListItem> Items = sourceList.GetItems("ProjectID", "Title", "ProjectName", "Featured", "Size", "Description")
.Cast<SPListItem>().AsEnumerable().OrderBy((i => rnd.Next()));
SPListItemCollection randProjImages = SPContext.Current.Web.Lists.TryGetList("Random Projects Images").GetItems();
var randomImgNrs = Enumerable.Range(0, randProjImages.Count).OrderBy(i => rnd.Next()).ToArray();
Dictionary<string, string> projectImages = new Dictionary<string,string>();
IEnumerable<SPListItem> projImages = SPContext.Current.Web.Lists.TryGetList("Assigned Projects Images").
GetItems().Cast<SPListItem>().AsEnumerable();
foreach (SPListItem it in projImages) projectImages.Add((string)it["ProjectID"], (string)it["ServerUrl"]);
int qCount = 0;
foreach (SPListItem item in Items) {
if (item["Size"] != null && item["Featured"]!=null &&
((string)item["Size"]).ToLower() == "big" || ((string)item["Featured"]).ToLower() == "yes") {
dataItems.Add(new Project(item["ProjectID"].ToString(), (string)item["Title"],
"/sites/Galileo/SitePages/" + Utils.getCurrentLang().ToLower() + "/Projects.aspx#id=pwp" + item["ProjectID"],
projectImages[(string)item["ProjectID"]],
Utils.truncateString(item.Fields["Description"].GetFieldValueAsText(item["Description"]), 175), "project"));
}else{
Replacing the foreach with this:
foreach (SPListItem item in Items) {
var k = item["Size"];
if (item["Size"] != null && item["Featured"]!=null &&
((string)item["Size"]).ToLower() == "big" || ((string)item["Featured"]).ToLower() == "yes") {
dataItems.Add(new Project(item["ProjectID"].ToString(), (string)item["Title"],
"/sites/Galileo/SitePages/" + Utils.getCurrentLang().ToLower() + "/Projects.aspx#id=pwp" + item["ProjectID"],
projectImages[(string)item["ProjectID"]],
Utils.truncateString(item.Fields["Description"].GetFieldValueAsText(item["Description"]), 175), "project"));
}else{
And breaking just before the if statement in the debugger, k == null
if (item["Size"] != null && item["Featured"]!=null &&
((string)item["Size"]).ToLower() == "big" || ((string)item["Featured"]).ToLower() == "yes")
it goes to the ((string)item["Featured"]).ToLower() == "yes")
No exception:
string a = null;
if (a != null && ((string) a).ToLower() == "boo")
string a = "";
if (a != null && ((string) a).ToLower() == "boo")
string a = "boo";
if (a != null && ((string) a).ToLower() == "boo")
this is as it should be (though the casting is unnecessary).
Does not compile:
T a = new T();
if (a != null && ((string) a).ToLower() == "boo")
T? a = null;
if (a != null && ((string) a).ToLower() == "boo")
T? a = new T();
if (a != null && ((string) a).ToLower() == "boo")
where T is any type other than string due to casting from T to string.
The real question is: Why do think it throws an exception?
Use
String.IsNullOrWhiteSpace(a)
You are right that the second argument of && is not evaluated if the first argument is false (a is null). So the code cannot throw a NullReferenceException. However, if a is not null but an object that cannot be cast to string, the code can throw an InvalidCastException.
Note that the best practice for comparing strings in a case-insensitive way is to use the String.Equals Method:
if (String.Equals(a, "foo", StringComparison.CurrentCultureIgnoreCase))
{
// ... operation
}
Since the method is static, no null-check is needed.
Exactly, this will not throw an exception. Since your expression is AND, evaluating only the first part is enough to know that it will never evaluate to true, so the second part is skipped.
Correct! (except that it's not called lazy evaluation)
If the first operand evaluates to true, the second operand isn't evaluated.
http://msdn.microsoft.com/en-us/library/vstudio/6373h346.aspx

How can I return a bool value from a plethora of nullable bools?

With this code:
private bool AtLeastOnePlatypusChecked()
{
return ((ckbx1.IsChecked) ||
(ckbx2.IsChecked) ||
(ckbx3.IsChecked) ||
(ckbx4.IsChecked));
}
...I'm stopped dead in my tracks with
Operator '||' cannot be applied to operands of type 'bool?' and 'bool?
So how do I accomplish this?
You can chain together |s, using the null-coalescing operator at the end:
return (ckbx1.IsChecked | cxbx2.IsChecked | cxbx3.IsChecked | cxbx4.IsChecked) ?? false;
The lifted | operator returns true if either operand is true, false if both operands are false, and null if either operand is null and the other isn't true.
It's not short-circuiting, but I don't think that'll be a problem for you in this case.
Alternatively - and more extensibly - put the checkboxes into a collection of some kind. Then you can just use:
return checkboxes.Any(cb => cb.IsChecked ?? false);
Try:
return ((ckbx1.IsChecked ?? false) ||
(ckbx2.IsChecked ?? false) ||
...
I'm assuming that if null, then it'll be false, you can use the ?? operator.
private bool AtLeastOnePlatypusChecked()
{
return ((ckbx1.IsChecked ?? false) ||
(ckbx2.IsChecked ?? false) ||
(ckbx3.IsChecked ?? false) ||
(ckbx4.IsChecked ?? false));
}
You can use GetValueOrDefault() to get either the value, or false.
private bool AtLeastOnePlatypusChecked()
{
return ((ckbx1.IsChecked.GetValueOrDefault()) ||
(ckbx2.IsChecked.GetValueOrDefault()) ||
(ckbx3.IsChecked.GetValueOrDefault()) ||
(ckbx4.IsChecked.GetValueOrDefault()));
}
You can use the following:
(ckbx1.IsChecked.HasValue && ckbx1.IsChecked.Value)
Use ?? operator inside your method;
private bool AtLeastOnePlatypusChecked()
{
return ((ckbx1.IsChecked ?? false) ||
(ckbx2.IsChecked ?? false) ||
(ckbx3.IsChecked ?? false) ||
(ckbx4.IsChecked ?? false)
}

LINQ List gives null exception in where Clause

var q = from p in query
where
((criterias.birthday == p.BirthDay|| criterias.birthday == null))
&& ((criterias.marriageDate == null || criterias.marriageDate == p.MarriageDate))
&& ((criterias.gender == p.Gender) || (criterias.gender == null))
&& ((criterias.nationalities.Contains(p.Nationality)) || (criterias.nationalities == null))
criterias isa class where i store my search criterias. nationalities is a string list. the problem occurs when i have no items in string. the query throws null reference exception. the query doesnt accept null value in nationalities. how can i fix this?
Reverse the order so that the null check comes before the query: as you're using ||, the second part of the expression is only evaluated when the first part evaluates to false:
&& ((criterias.nationalities == null) ||
(criterias.nationalities.Contains(p.Nationality)))
Look at these 2:
((criterias.birthday == p.BirthDay|| criterias.birthday == null))
&& ((criterias.marriageDate == null || criterias.marriageDate == p.MarriageDate))
I don't think marriageDate will give you problems but birthday uses the wrong order.
In this case you need the 'short-circuit evaluation' property of ||, change it to:
(criterias.birthday == null || criterias.birthday == p.BirthDay)
&& (criterias.marriageDate == null || criterias.marriageDate == p.MarriageDate)
Try swapping the order of the nationalties checks. It should short-circuit on the null check before it tries to evaluate the Contains.
((criterias.nationalities == null) || (criterias.nationalities.Contains(p.Nationality)))
Turn this statement around:
(criterias.nationalities.Contains(p.Nationality)) || (criterias.nationalities == null)
so that it reads
(criterias.nationalities == null) || (criterias.nationalities.Contains(p.Nationality))
If the first operand evaluates to true, the second one will be skipped.
Try first check for null then (if it is not null) check for contains:
var q = from p in query
where
((criterias.birthday == p.BirthDay|| criterias.birthday == null))
&& ((criterias.marriageDate == null || criterias.marriageDate == p.MarriageDate))
&& ((criterias.gender == p.Gender) || (criterias.gender == null))
&& ((criterias.nationalities == null) || (criterias.nationalities.Contains(p.Nationality))

Categories