I’m trying to execute the code below (in LINQPad), and my LINQ statement is getting an error
Cannot implicitly convert type
System.Collections.Generic.IEnumerable<UserQuery.ResultCode>toUserQuery.ResultCode.
Why?
Here is the code:
public enum ResultCode {
Big,
Bad,
Messy
}
public class ValidationResult {
public bool IsValid = false;
public ResultCode Code;
public override string ToString(){
return String.Format("IsValid: {0}, Code: {1}",IsValid, Code);
}
}
public class RuleMap {
public Func<bool> Fact;
public ResultCode Code;
public List<int> Actions;
}
public class RulesProcessor{
List<RuleMap> rules;
public RulesProcessor(){
rules = new List<RuleMap>{
new RuleMap {Fact = CheckLeft, Code = ResultCode.Big,
Actions = new List<int> {2, 3}
},
new RuleMap {Fact = CheckRight, Code = ResultCode.Bad,
Actions = new List<int> {1, 2}
},
new RuleMap {Fact = CheckDown, Code = ResultCode.Messy,
Actions = new List<int> {1, 3}
},
};
}
public bool CheckLeft(){
return true;
}
public bool CheckRight(){
return false;
}
public bool CheckDown(){
return true;
}
public ValidationResult EvaluateRulesOnAction(int actionType){
ValidationResult result = new ValidationResult();
ResultCode badRule = from foo in rules
where !foo.Fact() && foo.Actions.Contains(actionType)
select foo.Code;
if (badRule != null){
result.Code = badRule;
}else{
result.IsValid = true;
}
return result;
}
}
void Main()
{
var foo = new RulesProcessor();
foo.EvaluateRulesOnAction(1).Dump();
foo.EvaluateRulesOnAction(3).Dump();
}
The reason is that every LINQ query of the form
from x in y select xreturns anIEnumerable<TypeOfX>.If you are sure that there can be a maximum of one bad rule, you can change your code to this:
If there can be more than one bad rule but you are only interested in the first one, use this:
The “OrDefault” in both queries indicates that you want to have the default value of the returned type. For reference types this is
null.However, in your code, the query returns an enum of type
ResultCode. Enums can’t benull, so theifthat comes after the query will never yield the expected results asbadRule == nullis alwaysfalse.You should change your code to this: