I am trying to use FirstOrDefault
in my code but getting compile time error.
Cannot implicitly convert type
Priority
tobool
public class Priority
{
public string Name { get; set; }
public string Id { get; set; }
public string Default { get; set; }
}
public class ProcedureStatus
{
public string Id { get; set; }
public Priorities Priorities { get; set; }
}
public class Priorities
{
public List<Priority> Priority { get; set; }
}
foreach (Priority priority in status.Priorities.Priority)
{
if (priority.Default == "true" && grid.Priority == null)
{
grid.Priority = priority.Id;
grid.PriorityText = priority.Name;
SetPriority(gridRow);
break;
}
else if (status.Priorities.Priority.FirstOrDefault(x => x.Id == priority.Id))
priority.Default = "true";
}
How to use FirstOrDefault
in my scenario.
CodePudding user response:
Best way it's to compare if your object is not null after the research
foreach (Priority priority in status.Priorities.Priority)
{
if (grid.Priority == null)
{
grid.Priority = priority.Id;
grid.PriorityText = priority.Name;
break;
}
else if (status.Priorities.Priority.FirstOrDefault(x => x.Id == priority.Id) != null)
// You found something, do this.
}
Try it
CodePudding user response:
You are using status.Priorities.Priority.FirstOrDefault(x => x.Id == priority.Id)
in an if
clause.
The if
clause is expecting an expression that returns a bool
, but your expression returns a Priority
.
Aside from that, it looks like the if
clause is redundant, since you are iterating the properties via a foreach
and trying to get the current item from the list you are already iterating. If you just want to iterate the list, you don't need the if
clause.
The way you would typically use FirstOrDefault
would be like this:
var priority = status.Priorities.Priority.FirstOrDefault(x => x.Id == priorityId)`;
if (priority != null)
{
\\ ...
}
where priorityId
is the ID of the priority you are looking for.
This does not seem useful inside you foreach
loop though.
(Even after your question update, you still have the same if
clause inside the foreach
. It's just after an if
/else
now.)