36

以下のサンプルコードがありますが、おそらくをより適切に使用することで、これをよりクリーンにする方法を知りたいと思っていますSelectMany()。この時点で、QuestionListプロパティはnullになりません。私が欲しいのは、answerRowsそうではないリストですnullが、Questions時にはそうなることもありnullます。

IEnumerable<IQuestion> questions = survey.QuestionList
                    .Where(q => q.Questions != null)
                    .SelectMany(q => q.Questions);
            
if(questions == null)
return null;

IEnumerable<IAnswerRow> answerRows = questions
                    .Where(q => q.AnswerRows != null)
                    .SelectMany(q => q.AnswerRows);

if(answerRows == null)
return null;

とNullについてのJonのコメントに興味があったので、エラーがどこにあるかをより簡単に確認するために、いくつかの偽のデータを使用して例を試しEnumerable.SelectManyてみたかったのです。以下を参照してください。問題は、null参照を使用しないようにする必要があることでした。これは、実際に名前を読んだときに明らかです:(そして最後に物事をまとめました。SelectMany()SelectMany()SelectMany()NullReferenceException

また、これを行っている間にtry { } catch() { }、この例での使用は役に立たず、いつものようにJonSkeetが答えを持っていることに気付きました :)実行の延期。

したがって、行2の例外を確認したい場合は、関連する行1ビットをコメントアウトしてください:P、申し訳ありませんが、コード例を書き直さずにこのエラーを停止する方法を理解できませんでした。

using System;
using System.Collections.Generic;
using System.Linq;

namespace SelectManyExample
{
    class Program
    {
        static void Main(string[] args)
        {
            var questionGroupList1 = new List<QuestionGroup>() {
                new QuestionGroup() {
                    Questions = new List<Question>() {
                        new Question() {
                            AnswerRows = new List<AnswerRow>() {
                                new AnswerRow(),
                                new AnswerRow()
                            }
                        },

                        // empty question, causes cascading SelectMany to throw a NullReferenceException
                        null,

                        new Question() {
                            AnswerRows = new List<AnswerRow>() {
                                new AnswerRow() {
                                    Answers = new List<Answer>() {
                                        new Answer(),
                                        new Answer()
                                    }
                                }
                            }
                        }
                    }
                }
            };

            var questionGroupList2 = new List<QuestionGroup>() {
                null,
                new QuestionGroup()
            };

            IEnumerable<AnswerRow> answerRows1 = null;
            IEnumerable<AnswerRow> answerRows2 = null;

            try
            {
                answerRows1 = questionGroupList1
                    .SelectMany(q => q.Questions)
                    .SelectMany(q => q.AnswerRows);
            }
            catch(Exception e) {
                Console.WriteLine("row 1 error = " + e.Message);
            }

            try
            {
                answerRows2 = questionGroupList2
                    .SelectMany(q => q.Questions)
                    .SelectMany(q => q.AnswerRows);
            }
            catch (Exception e)
            {
                Console.WriteLine("row 2 error = " + e.Message);
            }


            Console.WriteLine("row 1: " + answerRows1.Count());
            Console.WriteLine("row 2: " + answerRows2.Count());
            Console.ReadLine();
        }


    }

    public class QuestionGroup {
        public IEnumerable<Question> Questions { get; set; }
    }

    public class Question {
        public IEnumerable<AnswerRow> AnswerRows { get; set; }
    }

    public class AnswerRow {
        public IEnumerable<Answer> Answers { get; set; }
    }

    public class Answer {
        public string Name { get; set; }
    }
}
4

3 に答える 3

64
survey.QuestionList
    .Where(l => l.Questions != null)
    .SelectMany(l => l.Questions)
    .Where(q => q != null && q.AnswerRows != null)
    .SelectMany(q => q.AnswerRows);

コレクションが決してnull. null上手く処理しないと大変なことになります。コード全体が終わっif (something != null) {}てしまいます。次に使用します。

survey.QuestionList
    .SelectMany(l => l.Questions)
    .SelectMany(q => q.AnswerRows);
于 2013-01-22T22:25:24.950 に答える
12
public static IEnumerable<TResult> SelectNotNull<TSource, TResult>(
    this IEnumerable<TSource> source, Func<TSource, IEnumerable<TResult>> selector)
    where TResult : class
{
    return source.Select(selector)
        .Where(sequence => sequence != null)
        .SelectMany(x => x)
        .Where(item => item != null);
}

これにより、次のことが可能になります。

var allAnswers = survey.QuestionList
    .SelectNotNull(list => list.Questions)
    .SelectNotNull(question => question.AnswerRows);
于 2013-01-22T22:38:03.363 に答える
11

DRY に準拠する解決策は、ラムダ式でnull 合体演算子を使用することです。??SelectMany

IEnumerable<IQuestion> questions = survey.QuestionList.SelectMany(q => q.Questions ?? Enumerable.Empty<IQuestion>());

IEnumerable<IAnswerRow> answerRows = questions.SelectMany(q => q.AnswerRows ?? Enumerable.Empty<IAnswerRow>());

OP のコードと上記のコードの両方で、 nullquestionsになることはないため、null チェックは必要ありません (ビジネス ロジックによってはチェックanswerRowsを入れたい場合があります)。.Any()ただし、上記のコードでも、q.Questionsorq.AnswerRowsが null の場合、例外が発生することはありません。

于 2019-07-01T08:36:27.353 に答える