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

C# 使用 LINQ 按输入值匹配CardNumber规则查询学生姓名功能求助

实现代码

public static string MultiplyListCheckUp (int InputValue)
{
    // 筛选所有符合规则的学生:输入值能被CardNumber的每一个元素整除
    var matchedList = StudentConfig
        .Where(s => s.CardNumber.All(num => InputValue % num == 0))
        .ToList();

    if (matchedList.Count > 1)
    {
        // 如需抛出异常可替换为:throw new InvalidOperationException("multi records occur");
        return "multi records occur";
    }

    return matchedList.Count == 1 ? matchedList.First().studentname : string.Empty;
}

逻辑说明

  • 核心匹配逻辑用LINQ的All方法实现:仅当学生的CardNumber数组中所有元素都能整除输入值时,才判定该学生匹配
  • 匹配结果处理:
    • 匹配数>1:按需求返回多记录提示,也可直接抛出异常
    • 匹配数=1:返回对应学生姓名
    • 匹配数=0:返回空字符串

注意事项

建议配置StudentConfig时保证CardNumber中所有值均为正整数,避免出现取模0的运算异常。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 22:48:00