2011-12-14 97 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));