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

如何统计LINQ返回的Module_Completion对象中值为true的属性数量以展示进度

实现方案

方案1:硬编码统计(推荐,性能最优,适合属性固定场景)

你当前需要统计的布尔属性数量是固定的7个,直接手动计数逻辑最简单,无额外性能开销:

// 先处理查询无结果的边界情况
if (obj == null)
{
    // 可根据业务需求自定义无记录时的展示内容
    string progressText = "Finished 0 of 7";
    return;
}

int totalCount = 7;
int trueCount = 0;

// 逐个统计为true的属性
if (obj.adv_stud_success) trueCount++;
if (obj.important_policies) trueCount++;
if (obj.technology) trueCount++;
if (obj.finances) trueCount++;
if (obj.resources) trueCount++;
if (obj.student_life) trueCount++;
if (obj.next_steps) trueCount++;

// 生成最终进度展示文本
string progressResult = $"Finished {trueCount} of {totalCount}";

方案2:反射动态统计(适合属性频繁变更的场景)

如果后续可能增减需要统计的布尔属性,不想每次修改计数逻辑,可以用反射自动遍历属性计算:

if (obj == null)
{
    string progressText = "Finished 0 of 7";
    return;
}

// 筛选出对象所有布尔类型的公共属性
var boolProps = obj.GetType()
                .GetProperties()
                .Where(p => p.PropertyType == typeof(bool))
                .ToList();

int totalCount = boolProps.Count;
int trueCount = boolProps.Count(p => (bool)p.GetValue(obj));

string progressResult = $"Finished {trueCount} of {totalCount}";

注意:该方案依赖你查询时select的匿名类仅包含需要统计的7个布尔属性,如果后续在select中新增其他非目标布尔属性,需要额外加属性名过滤规则。

方案3:LINQ查询阶段直接统计(性能最优,减少数据传输)

可以直接在数据库查询时完成统计,不需要把所有属性值回传到应用层:

var progressStats = db.Module_Completion
                .Where(r => r.star_id == User.Identity.Name)
                .Select(r => new 
                {
                    Total = 7,
                    Finished = 
                        (r.adv_stud_success ? 1 : 0) +
                        (r.important_policies ? 1 : 0) +
                        (r.technology ? 1 : 0) +
                        (r.finances ? 1 : 0) +
                        (r.resources ? 1 : 0) +
                        (r.student_life ? 1 : 0) +
                        (r.next_steps ? 1 : 0)
                })
                .FirstOrDefault();

string progressResult = progressStats == null ? "Finished 0 of 7" : $"Finished {progressStats.Finished} of {progressStats.Total}";

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 13:54:03