You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从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 doing a => a.courseId == courseDto.Id — this converts each entity into a boolean value (true if the ID matches, false otherwise). So x.Entities.Select(...) returns an IEnumerable<bool>, not a filtered list of entities.
  • The outer Select then turns each course in courseData.Courses into one of these boolean sequences, and FirstOrDefault() 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 Select when you want to transform items into something else (not for filtering).
  • Use Where or Any to filter items based on a condition.
  • SelectMany is handy for flattening nested collections like Courses -> Entities.

内容的提问来源于stack exchange,提问作者casillas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:26:14