返回字符串列表

Tom*_*Tom 3 c# linq

我需要修改下面提到的方法来返回字符串列表.它将以contactid作为输入,并应返回问卷清单

public string GetFatcaQuestionnaire(int contactId, string questionnaireType)
{
    using (var context = new dbDealingContainer())
    {
        if (context.Connection.State == ConnectionState.Closed)
            context.Connection.Open();

        var fatcaQuestionaires = context.FatcaQuestionaires.FirstOrDefault(p => p.ContactID == contactId && p.QuestionnaireType == questionnaireType);
        return fatcaQuestionaires != null ? fatcaQuestionaires.Questionaire : null;
    }
}
Run Code Online (Sandbox Code Playgroud)

新提出的方法

public List<string> GetFatcaQuestionnaire(int contactId)
{
    using (var context = new dbDealingContainer())
    {
        if (context.Connection.State == ConnectionState.Closed)
            context.Connection.Open();

        var fatcaQuestionaires = context.FatcaQuestionaires.Select(p => p.ContactID == contactId).ToList();
        return fatcaQuestionaires.ToList();
        //return fatcaQuestionaires.ToList() != null ? fatcaQuestionaires : null;
    }
}
Run Code Online (Sandbox Code Playgroud)

实际上只需要返回一个列表fatcaQuestonaires.Questionaire而不是整个fatcaQuestonaires对象.有人可以告诉我如何去做.

Mar*_*als 6

使用Linq,首先可以Where过滤所需的行,然后Select仅投影Questionaire属性.

试试这个

return context.FatcaQuestionaires
    .Where(p => p.ContactID == contactId)
    .Select(p => p.Questionaire)
    .ToList();
Run Code Online (Sandbox Code Playgroud)