2011-12-14 94 views
2

我有以下(工作)代码。这是非常不雅观的,我认为它可以使用Linq来重构,因此避免了foreach循环,并且不得不依赖外部列表<>。这个怎么做?由于在Linq中过滤出空值

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

回答

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(); 
+0

...的SelectMany我总是忘记它:)谢谢 – pistacchio 2011-12-14 09:44:58

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(); 
0
fillings.SelectMany(x => x.Answers.Where(a => a.Question == question) 
            .Select(a => a.Answer) 
            .FirstOrDefault()) 
     .Where(x => !string.IsNullOrEmpty(x));