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

C#使用LINQ查询Account表数据并生成按AccountName升序的Dictionary

LINQ版本实现方案

前置准备

首先你需要先通过ORM框架(推荐EF Core,也可以用LINQ to SQL)完成数据库Account表的实体映射,连接字符串沿用你原有配置里的SqlCon即可。

映射示例(EF Core)

using System.Configuration;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations.Schema;

// Account表实体映射
[Table("Account")]
public class Account
{
    public string AccountName { get; set; }
    public string Location { get; set; }
}

// 数据库上下文配置
public class AppDbContext : DbContext
{
    public DbSet<Account> Accounts { get; set; }
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(ConfigurationManager.ConnectionStrings["SqlCon"].ConnectionString);
    }
}

改造后的实现方法

public Dictionary<string, string> DisplayCustomerByLocation(string location)
{
    using (var dbContext = new AppDbContext())
    {
        // 查询语法实现,和你原有SQL逻辑完全等价
        return (from acc in dbContext.Accounts
                where acc.Location == location
                orderby acc.AccountName ascending
                select acc)
                .ToDictionary(
                    acc => acc.AccountName,  // 指定字典的Key
                    acc => acc.Location      // 指定字典的Value
                );
    }
}

如果你更偏好方法链写法,也可以用等价的实现:

public Dictionary<string, string> DisplayCustomerByLocation(string location)
{
    using (var dbContext = new AppDbContext())
    {
        return dbContext.Accounts
            .Where(acc => acc.Location == location)
            .OrderBy(acc => acc.AccountName)
            .ToDictionary(acc => acc.AccountName, acc => acc.Location);
    }
}

注意事项

  • 该实现会自动生成参数化SQL,和你原有ADO.NET的SQL逻辑完全一致,不存在SQL注入风险
  • 和你原有代码行为一致,如果AccountName存在重复值,ToDictionary会抛出异常,如果业务上允许重复账号名,可以改用ToLookup实现,或者先调用Distinct去重
  • 上下文的using块会自动管理数据库连接的生命周期,不需要手动编写打开、关闭连接的代码
  • 如果你用的是LINQ to SQL框架,只需要把上下文替换为你生成的DataContext实例即可,查询逻辑不需要修改

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 13:57:00