简体   繁体   中英

Filter out null values in Linq

I have the following (working) code. It is very inelegant, and I think it can be refactored using Linq only and hence avoiding the foreach loop and having to rely on an external List<>. How to do this? Thanks

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

Or if you need a list:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM