我已经用谷歌搜索了一段时间,并尝试了各种类型的组合来解决我的问题。
我想用我的匿名类型的结果填充我的 Gridview。“循环”中的第一次运行很顺利,因为所有变量都有一些实际值。
但第二次填充第 2 行时抛出:对象引用未设置为对象的实例。
这是因为我可能将一个匿名对象分配给 null 并且 gridview 无法处理它。我试图找出一些解决方案,但还没有解决。
是否有正确理解 LinQ 的秘密通道?
这是我现在的代码:
var filteredlist = from info in list // List from external
select new
{
Question = info.QuestionText ?? "Test",
CorrectAnswer = info.CorrectAnswer.OptionText ?? "Test",
WrongAnswer1 = info.WrongAnswer1.OptionText ?? "Test",
WrongAnswer2 = info.WrongAnswer2.OptionText ?? "Test", //Throws Error
WrongAnswer3 = info.WrongAnswer3.OptionText ?? "Test" //Throws Error
};
GridView1.DataSource = filteredlist;
GridView1.DataBind();
这是我试图让它发挥作用。
var filteredlist = from info in list // list from external
select new
{
Question = info.QuestionText == null ? "Test" : info.QuestionText,
CorrectAnswer = info.CorrectAnswer.OptionText == null ? "Test" : info.CorrectAnswer.OptionText,
WrongAnswer1 = info.WrongAnswer1.OptionText == null ? "Test" : info.WrongAnswer1.OptionText,
WrongAnswer2 = info.WrongAnswer2.OptionText == null ? "Test" : info.WrongAnswer2.OptionText, //Throws Error
WrongAnswer3 = info.WrongAnswer3.OptionText == null ? "Test" : info.WrongAnswer3.OptionText, //Throws Error
};
GridView1.DataSource = filteredlist;
GridView1.DataBind();
第二次尝试
var filteredlist = from info in list // list from external
select new
{
Question = info.QuestionText != null ? "Test" : info.QuestionText,
CorrectAnswer = info.CorrectAnswer.OptionText != null ? "Test" : info.CorrectAnswer.OptionText,
WrongAnswer1 = info.WrongAnswer1.OptionText != null ? "Test" : info.WrongAnswer1.OptionText,
WrongAnswer2 = info.WrongAnswer2.OptionText != null ? "Test" : info.WrongAnswer2.OptionText, //Throws Error
WrongAnswer3 = info.WrongAnswer3.OptionText != null ? "Test" : info.WrongAnswer3.OptionText, //Throws Error
};
GridView1.DataSource = filteredlist;
GridView1.DataBind();