从courseData列表获取课程时代码返回布尔值的技术咨询
Why Your Code Returns a Boolean & How to Fix It
Hey there! Let's break down why your current code is spitting out a boolean instead of the course/entity you're targeting, and fix it up.
The Root Cause
Your code has a key mix-up between Select and filtering methods:
- Inside your nested
Select, you're doinga => a.courseId == courseDto.Id— this converts each entity into a boolean value (true if the ID matches, false otherwise). Sox.Entities.Select(...)returns anIEnumerable<bool>, not a filtered list of entities. - The outer
Selectthen turns each course incourseData.Coursesinto one of these boolean sequences, andFirstOrDefault()grabs the first boolean from the first sequence. That's why you're getting a boolean back!
Fixes Based on What You Need
Let's adjust the code depending on your end goal:
1. Get the specific entity that matches the course ID
If you want the actual entity with the matching courseId, flatten the entities and filter directly:
var matchedEntity = courseData.Courses .SelectMany(course => course.Entities) // Flatten all nested entities into a single list .FirstOrDefault(entity => entity.courseId == courseDto.Id);
2. Get the course that contains the matching entity
If you need the parent course that has an entity with the target ID:
var matchedCourse = courseData.Courses .FirstOrDefault(course => course.Entities.Any(entity => entity.courseId == courseDto.Id));
Here, Any() checks if the course has at least one entity with the matching ID, which is what we want for filtering.
3. Get both the course and its matching entity
If you need both the parent course and the specific entity inside it:
var courseAndEntity = courseData.Courses .Where(course => course.Entities.Any(entity => entity.courseId == courseDto.Id)) .Select(course => new { Course = course, MatchedEntity = course.Entities.First(entity => entity.courseId == courseDto.Id) }) .FirstOrDefault();
Quick Recap
- Use
Selectwhen you want to transform items into something else (not for filtering). - Use
WhereorAnyto filter items based on a condition. SelectManyis handy for flattening nested collections likeCourses -> Entities.
内容的提问来源于stack exchange,提问作者casillas
相关产品推荐
相关产品推荐

