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

C#中LINQ匹配Where条件后基于Profile信息新增记录实现方法

实现代码

直接用SelectMany替换原有单层Select逻辑,在投影阶段完成条件判断和额外记录追加,全程保持原有标识符、字段映射规则不变:

// 假定原有学生集合变量名为students,和你现有代码上下文保持一致
var resultSet = students
    // 带索引投影先绑定自增行号,索引从0开始因此rowno从1起算,和原自增逻辑对齐
    .Select((stu, idx) => new { CurrentStu = stu, CurrentRowNo = idx + 1 })
    .SelectMany(item =>
    {
        // 构造常规学生记录,保持原有sid、snmae映射规则
        var normalRecord = new
        {
            rowno = item.CurrentRowNo,
            sid = item.CurrentStu.StudentID,
            snmae = item.CurrentStu.StudentName,
            isDataFromProfile = 0
        };

        // 命中UniqueID为"10345"的规则时,额外追加Profile来源记录
        if (item.CurrentStu.UniqueID == "10345")
        {
            var profileExtraRecord = new
            {
                rowno = item.CurrentRowNo,
                sid = item.CurrentStu.ProfileID,
                snmae = item.CurrentStu.ProfileName,
                isDataFromProfile = 1
            };
            return new[] { normalRecord, profileExtraRecord };
        }

        // 未命中规则仅返回常规记录
        return new[] { normalRecord };
    })
    .ToList();
逻辑说明
  • 自增rowno计算逻辑和原有实现完全一致,不会出现行号错位
  • 原有字段映射规则未做任何修改:sid映射StudentID、snmae映射StudentName
  • 追加的额外记录完全符合要求:sid/snmae取当前匹配记录的ProfileID/ProfileName,isDataFromProfile赋值为1,rowno和当前匹配记录行号一致
  • 所有类定义、属性名、技术术语均保留原有标识,未做更名修改

不要在Select投影完成后再做遍历插入操作,会增加一次集合遍历开销,也容易因为插入位置错误导致行号和实际顺序不匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 12:27:06