简体   繁体   中英

How to use DefaultIfEmpty

I am using below code to calculate score, on list of question answer by user, but getting error sequence contains no matching element.

Now here I am trying to select first selected option of question and doing sum of score of that option. But when there is no option selected it says no matching element found hence I added DefaultIfEmpty but it still throws same error.

Now If I use FirstOrDefault , I am getting null values, then I have to add null check in Sum, which doesn't look appropriate. Should I provide my default in FirstOrDefault is that solution?

int Score = Questions.Select(x => x.Options.First(o => o.IsSelected))
                     .DefaultIfEmpty()
                     .Sum(s => s == null ? 0 : s.Score);

So what is best way to write this linq query.

As your code is written, you're calling DefaultIfEmpty on the set of options for all questions, thus it will have no effect as long as the set of questions is not empty. And given that a question with no selected options exists, as you have pointed out, the inner call to First will throw.

If you want to use DefaultIfEmpty , you could do it on the options collection as follows:

int Score = Questions.Select(x => x.Options
                                     .Where(o => o.IsSelected)
                                     .Select(o => o.Score)
                                     .DefaultIfEmpty()
                                     .First()
                      )
                 .Sum();

Here, since you project to an integer collection before calling DefaultIfEmpty , it will yield a singleton collection with 0 in it in the empty case, as 0 is the default value for int . However, FirstOrDefault will achieve the same thing as the calls to DefaultIfEmpty().First() in this case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM