LINQ:按id从对象数组中选择单个值

时间:2015-09-25 08:26:35

标签: c# arrays linq class object

采用以下示例类:

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,我希望获得指定Answer的{​​{1}}。例如,如果我给QuestionId 2,则结果为'John'。

我希望能够找出特定问题的答案来填充单独的DTO。即:

QuestionId

到目前为止,我只是设法使用以下内容获得答案:

var person = new PersonDto {Name = <single line LINQ goes here>};

这可能在一行代码中吗?

2 个答案:

答案 0 :(得分:7)

可以使用例如来自Linq的Single Single会在有多个答案时抛出异常。

var answer = questionArray.Single(x=>x.QuestionId == 2).Answer;

这个答案假设一个问题只有一个答案(并且总是存在)。如果您不确定是否存在答案,则可以添加SingleOrDefault并检查是否为null。或者您可以添加Where子句以获得多个答案,例如:

var answers = questionArray.Where(x=>x.QuestionId == 2).Select(x=>x.Answer);

如果没有问题的答案,上面的代码段不会失败,它将返回空序列。您可以测试它是否有值并在其上运行First

答案 1 :(得分:3)

您使用的是错误的(t​​m)数据类型。对于像这样的查找,请使用词典。

public class Question // Class names should be a singular form noun
{
    public int Id { get; set; } // QuestionId is redundant
    public string Question { get; set; }
    public string Answer { get; set; }
}

var questions = new Question[]
{
    new Questions {Id = 1, Question = "How old are you?", Answer = "32"},
    new Questions {Id = 2, Question = "What is your name?", Answer = "John"},
    new Questions {Id = 3, Question = "How tall are you?", Answer = "6'"}
}.ToDictionary(q => q.Id, q => q);

var answerToQuestionNumberTwo = questions[2].Answer;

编辑:澄清,字典在这里“更好”的原因是因为它更具可读性和更快。您希望构建一个用于将问题与给定ID相关联的集合,使您能够对问题对象进行查找以查询其属性。这是Dictionary数据结构的存在理由,它的查找时间复杂度为O(1)(与Where / First / Single LINQ方法的O(n)相比)。