36

我有下面的示例代码,我很想知道如何让这个更干净,可能通过更好地使用SelectMany(). 此时该QuestionList属性不会为空。我想要的只是一个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;

我对 Jon 对Enumerable.SelectMany和 Null 的评论很感兴趣。所以我想用一些假数据尝试我的示例,以便更容易地查看错误在哪里,请参阅下文,特别是我如何使用SelectMany()a 的结果SelectMany(),它更清楚我现在的问题是必须确保您不要SelectMany()在空引用上使用,当我实际阅读NullReferenceException名称时很明显:( 最后将它们放在一起。

同样在执行此操作时,我意识到try { } catch() { }在此示例中使用 是无用的,并且像往常一样 Jon Skeet 有答案 :) 延迟执行..

因此,如果您想查看第 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 的解决方案是在lambda 表达式中使用null-coalescing 运算符。??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 的代码和上面的代码中,questions并且answerRows永远不会为 null,因此不需要进行 null 检查(您可能希望.Any()根据您的业务逻辑进行检查)。q.Questions但是如果或q.AnswerRows为空,上面的代码也永远不会导致异常。

于 2019-07-01T08:36:27.353 回答