Using nullable types in Linq expressions
var quantSubset =
from userAns in userAnalysis.AllUserAnswers
join ques in userAnalysis.AllSeenQuestions on userAns.QID equals ques.QID
where (ques.QuestionType == "QT")
select new {
QuestionLevel = ques.LevelID,
TimeTaken = userAns.TimeTaken,
Points = userAns.P开发者_JAVA技巧oints,
UsedWeapon = (userAns.UsedBy2 && userAns.UsedHint),
WasCorrect = userAns.WasCorrect.HasValue ? userAns.WasCorrect.Value : null
};
In my select expression I want to select a nullable type WasCorrect (last part of the expression) but apparently I cannot do it the way I am currently trying.
How can I get WasCorrect as nullable type
I tried ?WasCorrect but that also doesnt gives error in Visual Studio.
You need to cast the null
value to the nullable type explicitly:
WasCorrect = userAns.WasCorrect.HasValue ?
userAns.WasCorrect.Value : (TheTypeName?)null
Otherwise C# won’t know which type the conditional expression should be.
Apart from that, the code is completely redundant. You can simply write:
WasCorrect = userAns.WasCorrect
You absolutely must be able to write
select new { WasCorrect = userAns.WasCorrect }
if userAns.WasCorrect
is Nullable<bool>
.
This code executes without a problem:
class Test {
public bool? NullableBool { get; set;}
}
class MainClass
{
public static void Main ()
{
Test t1 = new Test { NullableBool = true };
var a1 = new { NB = t1.NullableBool };
Test t2 = new Test { NullableBool = null };
var a2 = new { NB = t2.NullableBool };
}
}
精彩评论