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

SQL存储过程转C# LINQ:集合选择与LINQ实现咨询

解决方案

1. 定义数据存储结构

先创建一个类对应原SQL临时表的两个字段,方便后续存储和操作数据:

// 根据数据库实际字段类型调整属性(比如Code是int就改成int类型)
public class CodeCountItem
{
    public string Code { get; set; }
    public int Count { get; set; }
}

2. 集合选择

推荐用List<CodeCountItem>作为存储集合:

  • 它实现了IList<T>和IEnumerable<T>接口,支持随机访问、遍历等操作
  • 是.NET中最常用的内存集合类型,操作简单高效,完全满足后续while循环遍历的需求

3. LINQ实现SQL逻辑

基于Entity Framework,有两种写法对应原SQL逻辑:

写法1:对应原SQL的子查询风格

using (var dbContext = new YourDbContext()) // 替换成你的EF上下文类
{
    var codeCountList = dbContext.Table1
        // 过滤table1中table1Property为1的记录
        .Where(t1 => t1.Table1Property == true)
        .Select(t1 => new CodeCountItem
        {
            Code = t1.Code,
            // 统计table2中对应Code的EntryID数量
            Count = dbContext.Table2.Count(t2 => t2.Code == t1.Code)
        })
        .ToList(); // 立即执行查询并加载到内存集合中
}

写法2:用GroupJoin优化查询(生成更高效的JOIN型SQL)

如果数据量较大,这种写法生成的SQL性能通常更优:

using (var dbContext = new YourDbContext())
{
    var codeCountList = dbContext.Table1
        .Where(t1 => t1.Table1Property == true)
        .GroupJoin(
            dbContext.Table2,
            t1 => t1.Code, // table1的关联字段
            t2 => t2.Code, // table2的关联字段
            (t1, t2Group) => new CodeCountItem
            {
                Code = t1.Code,
                Count = t2Group.Count() // 统计分组后的记录数
            })
        .ToList();
}

4. 遍历执行操作

while循环方式

int currentIndex = 0;
while (currentIndex < codeCountList.Count)
{
    var currentItem = codeCountList[currentIndex];
    if (currentItem.Count > 0)
    {
        // 执行Count大于0时的操作
    }
    else
    {
        // 执行Count等于0时的操作
    }
    currentIndex++;
}

更简洁的foreach方式(推荐)

如果没有特殊需求,foreach比while更易读:

foreach (var item in codeCountList)
{
    if (item.Count > 0)
    {
        // 执行对应操作
    }
    else
    {
        // 执行对应操作
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 11:20:07