Using nullable types in Linq expressions

穿精又带淫゛_ 提交于 2019-12-22 08:45:25

问题


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.Points,
        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.


回答1:


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



回答2:


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 };
    }
}


来源:https://stackoverflow.com/questions/3821054/using-nullable-types-in-linq-expressions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!