C# 过滤掉Linq中的空值

C# 过滤掉Linq中的空值,c#,linq,C#,Linq,我有以下(工作)代码。它非常不雅观,我认为它可以仅使用Linq进行重构,从而避免foreach循环,并且必须依赖外部列表。如何做到这一点?谢谢 List<string> answerValues = new List<string>(); foreach (Fillings filling in fillings) { string answer = filling.Answers.Where(a => a.Questions == ques

我有以下(工作)代码。它非常不雅观,我认为它可以仅使用Linq进行重构,从而避免
foreach
循环,并且必须依赖外部列表。如何做到这一点?谢谢

  List<string> answerValues = new List<string>();
  foreach (Fillings filling in fillings)
  {
      string answer = filling.Answers.Where(a => a.Questions == question)
          .Select(a => a.Answer).FirstOrDefault();
      if (!string.IsNullOrEmpty(answer)) answerValues.Add(answer);
  }
List answerValues=new List();
foreach(填充物填充物)
{
字符串答案=填充.答案.其中(a=>a.问题==问题)
.Select(a=>a.Answer).FirstOrDefault();
如果(!string.IsNullOrEmpty(answer))answerValues.Add(answer);
}
IEnumerable answerValues=填充
.选择多个(f=>f.答案)
.其中(a=>a.问题==问题)
.选择(a=>a.答案)
.Where(ans=>!string.IsNullOrEmpty(ans));
或者,如果您需要列表:

IList<string> answerValues = fillings
                                    .SelectMany(f => f.Answers)
                                    .Where(a => a.Questions == question)
                                    .Select(a => a.Answer)
                                    .Where(ans => !string.IsNullOrEmpty(ans))
                                    .ToList();
IList answerValues=填充
.选择多个(f=>f.答案)
.其中(a=>a.问题==问题)
.选择(a=>a.答案)
.Where(ans=>!string.IsNullOrEmpty(ans))
.ToList();
IList<string> answerValues = fillings
                                    .SelectMany(f => f.Answers)
                                    .Where(a => a.Questions == question)
                                    .Select(a => a.Answer)
                                    .Where(ans => !string.IsNullOrEmpty(ans))
                                    .ToList();
var answerValues = (
    from f in fillings
    from a in f.Answers
    where a.Question == question
    where !String.IsNullOrEmpty(a.Answer)
    select a.Answer).ToList();
fillings.SelectMany(x => x.Answers.Where(a => a.Question == question)
                                  .Select(a => a.Answer)
                                  .FirstOrDefault())
        .Where(x => !string.IsNullOrEmpty(x));