LINQ Query to Select Questions with Selected Options in Nested Questionnaire Structure
GreatlyUnknown seeks advice on writing a LINQ query to retrieve questions with selected options from a nested questionnaire structure, sparking a discussion about effective usage of SelectMany in C#.
LINQ Query to Select Questions with Selected Options in Nested Questionnaire Structure
Author: GreatlyUnknown
Problem Statement
A questionnaire has the following nested structure:
- Categories
- Sections
- Questions
- Options (each can be selected or not)
- Questions
- Sections
The goal is to collect all Question
objects with at least one selected Option
, avoiding deeply nested foreach loops in favor of a LINQ-based approach.
Example LINQ Solutions
Participants suggested using SelectMany
and Where
:
var questionsWithAtLeastOneSelectedOption =
categories
.SelectMany(c => c.Sections)
.SelectMany(s => s.Questions)
.Where(q => q.Options.Any(o => o.IsSelected));
Or, more succinctly (if query syntax is preferred):
var questionsWithSelected =
from c in categories
from s in c.Sections
from q in s.Questions
where q.Options.Any(o => o.IsSelected)
select q;
Key Notes
- SelectMany flattens nested collections, making it effective for traversing multi-level data.
- Where allows filtering to questions that meet the criteria (at least one option selected).
Community Takeaways
- Use of
SelectMany
is standard for this kind of nested selection in C#. - Remembering key LINQ operators helps keep code concise and readable.
- Some participants advocate using AI tools for such queries, though traditional community support is still valued.
Summary
If working with a nested questionnaire structure in C#, use SelectMany
and Where
to efficiently filter for questions with selected options, avoiding cumbersome nested loops.
References:
This post appeared first on “Reddit CSharp”. Read the entire article here