Can I somehow connect two assignments to temp into one condition (with &) in the if statement?
node temp = new node();
temp = queue.Find(match => match.Check_node_state(element.state));
if (temp == null)
temp = explored_nodes.Find(match => match.Check_node_state(element.state));
if (temp == null)
You can chain the null coalescing operator.
node temp = queue.Find(match => match.Check_node_state(element.state))
?? explored_nodes.Find(match => match.Check_node_state(element.state))
?? someOtherFind()
?? anotherFind();
if (temp == null)
throw new Exception("This thing really does not exist!");
In C#, the operator you want is ?? which allows you to provide an alternate value in case the first is null. The statement would look something like this:
node temp = queue.Find(match => match.Check_node_state(element.state))
?? explored_nodes.Find(match => match.Check_node_state(element.state));
Well, you certainly can do:
if (queue.Find(match => match.Check_node_state(element.state)) == null &&
explored_nodes.Find(match => match.Check_node_state(element.state)) == null)
But I don't see it as a huge improvement...
Note that you need to use && instead of & to make the code equivalent because && short-circuits, while & will evaluate both conditions even if the first is true.
You can use Any to make code even more readable:
if (!queue.Any(match => match.Check_node_state(element.state)) &&
!explored_nodes.Any(match => match.Check_node_state(element.state)))
Related
if statement to check the value of an attribute doesn't work.
if (element.Elements(ns + "list").Where(x => x.Attribute("name").Value == "myProject") != null)
Is there other way to check if the value of an attribute exists?
you can use firstordefault
var element = element.Elements(ns + "list").Where(x => x.Attribute == "myProject");
// return if null
if(element == null) return;
// do your stuff
Sorry for messy indentation as I'm typing on mobile :)
In the below code, if i uncomment the line starting with queItem.RequestedMap == null I get
Non-static method requires a target.
If I then instead rewrite it as it is now, with a .ToList() and then doing the same where query after that it works. This tells me that .net is not able to translate the null check of queItem.RequestedMap == null into something sql specific.
queItem is an object paramater passed to the method containing this code.
Is there a way I can write this without retrieving the data back to .net and then doing another where? The existing answers I found just said to remove such expressions from the lambda query, which I dont want to do.
var gameToJoin = db.Games
//.Where(x =>
// (queItem.RequestedMap == null || x.Map.Id == queItem.RequestedMap.Id) // no map preference or same map
//)
.ToList()
.Where(x =>
queItem.RequestedMap == null
|| x.Map.Id == queItem.RequestedMap.Id) // no map preference or same map)
.FirstOrDefault();
Edit: Also, in the real query expression there are multiple other expressions in the first .Where that is commented here, they always need to be checked.
var gameToJoin = db.Games.AsQueryable();
// add the where's that always need to be checked.
if (queItem.RequestMap != null)
{
gameToJoin = gameToJoin.Where(x => x.Map.Id = queItem.RequestMap.Id);
}
var result = gameToJoin.ToList();
Or if you'd rather use FirstOrDefault()
var gameToJoin = db.Games.AsQueryable();
// add the where's that always need to be checked.
if (queItem.RequestMap != null)
{
var result = new List<Game>();
var game = gameToJoin.FirstOrDefault(x => x.Map.Id = queItem.RequestMap.Id);
if (game != null)
{
result.Add(game);
}
return result;
}
return gameToJoin.ToList();
Wouldn't this produce what you want? I don't see a reason that queItem.RequestedMap check should be a part the LINQ, because it is not a part the database.
Game gameToJoin = null;
if(queItem.RequestedMap == null)
{
gameToJoin = db.Games
.Where(x => x.Map.Id == queItem.RequestedMap.Id)
.FirstOrDefault;
}
Ive been having some trouble trying to get this linq statement to work. I am setting up a search using linq queries. What i want to do is if a search is null or empty, have it ignore that part of the filtering. So what i have set up is many where clauses that short circuit the where clause like so:
tvContent.LoadContent(
Live.Ringtones
.Where(x => cbSeller.SelectedValue== null ||
x.Property.SellerID == (int)cbSeller.SelectedValue)
.Where(x => cbProperty.SelectedValue==null ||
x.PropertyID == (int)cbProperty.SelectedValue)
.Where(x => string.IsNullOrEmpty(tbContentID.Text) ||
x.RingtoneID == ContentID)
.Where(x => string.IsNullOrEmpty(tbContentName.Text) ||
x.RingtoneName == tbContentName.Text).ToList());
But when I do this I keep getting null reference issues.
cbProperty, is empty, and selectedValue does show up null when I debug, but it still says there's a null reference issue. What am I doing wrong?
Why are you putting an invariant into the where clauses?
var ringtones = Live.Ringtones;
if (cbSeller.SelectedValue!= null)
ringtones = ringtones.Where(x=> x.Property.SellerID
== (int)cbSeller.SelectedValue);
if (cbProperty.SelectedValue!= null)
ringtones = ringtones.Where(x=> x.PropertyID
== (int)cbProperty.SelectedValue);
if(!string.IsNullOrEmpty(tbContentID.Text))
ringtones.Where(x=> x.RingtoneID == ContentID)
if(!string.IsNullOrEmpty(tbContentName.Text) )
ringtones.Where(x => x.RingtoneName == tbContentName.Text)
tvContent.LoadContent(ringtones.ToList());
I have an list of objects that contains another object in it.
List<MyClass> myClass = new List<MyClass>();
I want to do some linq like this
myClass.Where(x => x.MyOtherObject.Name = "Name").ToList();
Thing is sometimes "MyOtherObject" is null. How do I check for this?
Simple, just add an AND clause to check if it's not null:
myClass.Where(x => x.MyOtherObject != null && x.MyOtherObject.Name = "Name").ToList();
As of C# 6, you can also use a null conditional operator ?.:
myClass.Where(x => x.MyOtherObject?.Name == "Name").ToList();
This will essentially resolve the Name property to null if MyOtherObject is null, which will fail the comparison with "Name".
Try it online
You can just make your predicate check for null...
myClass.Where(x => (x.MyOtherObject == null) ? false : x.MyOtherObject.Name == "Name").ToList();
I would do something like this:
myClass.Where(x => x.MyOtherObject != null)
.Where(y => y.MyOtherObject.Name = "Name")
.ToList();
I have the following LINQ expression that's not returning the appropriate response
var query = from quote in db.Quotes
where quote.QuoteStatus == "Estimating" || quote.QuoteStatus == "Rejected"
from emp in db.Employees
where emp.EmployeeID == quote.EmployeeID
orderby quote.QuoteID descending
select new
{
quote.QuoteID,
quote.DateDue,
Company = quote.Company.CompanyName,
Attachments = quote.Attachments.Count,
Employee = emp.FullName,
Estimator = (quote.EstimatorID != null && quote.EstimatorID != String.Empty)
? db.Employees.Single (c => c.EmployeeID == quote.EstimatorID).FullName
: "Unassigned",
Status = quote.QuoteStatus, Priority = quote.Priority
};
The problem lies in the Estimator = (quote.EstimatorID != null && quote.EstimatorID != String.Empty) ? db.Employees.Single(c => c.EmployeeID == quote.EstimatorID).FullName : "Unassigned" part.
I NEVER get it to evalueate to "Unassigned", on the ones that are supposed to, it just returns null. Have I written this wrong?
Try this and see if you're receiving the same values:
Estimator = ((!string.IsNullOrEmpty(quote.EstimatorID) && !string.IsNullOrEmpty(quote.EstimatorID.Trim())
? (db.Employees.Single(c => c.EmployeeID == quote.EstimatorID)).FullName
: "Unassigned")
If that doesn't work, try replacing the check in the ternary expression (!string.IsNullOrEmpty part) with false and see if you reach "Unassigned". I've found that sometimes, when you use a ternary expression in a LINQ query, you have to wrap the whole thing in parentheses.
I think your expression is correct, although I would advise changing it to !string.IsNullOrEmpty(quote.EstimatorID) for clarity.
Note however that your expression could still return null if db.Employees.Single(c => c.EmployeeID == quote.EstimatorID).FullName returns null.
Then it looks like quote.EstimatorID is not null or empty string. Is db.Employees.Single() returning null here? Debug it - put breakpoints into those parts of the expression (putting them on separate lines, if necessary). If you can't do that wrap methods around them that call Debug.WriteLine() or similar.