2011-12-14 10 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

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)); 
関連する問題