在Linq中过滤掉空值

时间:2011-12-14 09:37:00

标签: c# linq

我有以下(工作)代码。它非常不优雅,我认为它只能使用Linq重构,因此避免了foreach循环并且不得不依赖外部List<>。这该怎么做?谢谢

  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);
  }

3 个答案:

答案 0 :(得分:4)

IEnumerable<string> answerValues = fillings
                                    .SelectMany(f => f.Answers)
                                    .Where(a => a.Questions == question)
                                    .Select(a => a.Answer)
                                    .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();

答案 1 :(得分:0)

var answerValues = (
    from f in fillings
    from a in f.Answers
    where a.Question == question
    where !String.IsNullOrEmpty(a.Answer)
    select a.Answer).ToList();

答案 2 :(得分:0)

fillings.SelectMany(x => x.Answers.Where(a => a.Question == question)
                                  .Select(a => a.Answer)
                                  .FirstOrDefault())
        .Where(x => !string.IsNullOrEmpty(x));