【发布时间】:2015-09-25 08:26:34
【问题描述】:
以下面的类为例:
public class Questions
{
public Int32 QuestionId { get; set; }
public String Question { get; set; }
public String Answer { get; set; }
}
还有以下数组:
var questionArray = new Questions[]
{
new Questions {QuestionId = 1, Question = "How old are you?", Answer = "32"},
new Questions {QuestionId = 2, Question = "What is your name?", Answer = "John"},
new Questions {QuestionId = 3, Question = "How tall are you?", Answer = "6'"}
};
使用 LINQ,我想获取指定 QuestionId 的 Answer。例如,如果我给QuestionId 2,则结果将是 'John'。
我希望能够提取特定问题的答案以填充单独的 DTO。即:
var person = new PersonDto {Name = <single line LINQ goes here>};
到目前为止,我只能使用以下方法得到答案:
foreach (var q in questionArray.Where(q => q.QuestionId == 2))
{
var answer = q.Answer;
}
这可以在 1 行代码中实现吗?
【问题讨论】:
-
是的,这是可能的。到目前为止,您尝试过什么?
-
@Dom84 用我试过的代码更新了问题。
-
所以 QuestionId 在这种情况下不是唯一的吗?那么你决定采用一个特定的元素是什么?
-
@Dom84 QuestionId 始终是唯一的。我已经用更多信息再次更新了这个问题。
标签: c# arrays linq class object