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

C# 使用Linq将数据库Negative类型对应的Quantity转为负数值

实现方案

共有两种常用的实现方式,可根据你的业务场景选择:

方案1:Linq查询阶段处理(推荐)

直接在查询的投影逻辑中对Quantity做符号转换,代码侵入性低,和现有逻辑耦合度小:

场景A:直接绑定GridView无需复用原实体

可以投影为匿名类,不需要额外定义DTO:

// 注意修正原代码中的笔误:Class.Negative 应为 ClassType.Negative
var objects = db.Objects
    .Where(x => x.Type == ClassType.Positive || x.Type == ClassType.Negative)
    .AsNoTracking()
    .Select(so => new 
    {
        so.Id,
        so.Type,
        // 其他需要在GridView展示的字段逐一补充
        Quantity = so.Type == ClassType.Negative ? -so.Quantity : so.Quantity
    })
    .ToList();

场景B:需要保留原实体类结构

直接投影为原Objects实体类即可:

var objects = db.Objects
    .Where(x => x.Type == ClassType.Positive || x.Type == ClassType.Negative)
    .AsNoTracking()
    .Select(so => new Objects
    {
        Id = so.Id,
        Type = so.Type,
        // 其他需要保留的字段逐一赋值
        Quantity = so.Type == ClassType.Negative ? -so.Quantity : so.Quantity
    })
    .ToList();

场景C:数据量较小,担心EF无法解析三元运算

可以先将筛选后的数据加载到内存再修改:

var objects = db.Objects
    .Where(x => x.Type == ClassType.Positive || x.Type == ClassType.Negative)
    .AsNoTracking()
    .ToList()
    .ForEach(so => 
    {
        if (so.Type == ClassType.Negative)
        {
            so.Quantity = -so.Quantity;
        }
    });

注:原代码中的Select(so=> so).AsQueryable()为冗余逻辑,可直接删除不影响功能

方案2:GridView绑定阶段处理

如果不想修改现有查询逻辑,可以在GridView的RowDataBound事件中做显示转换:

protected void YourGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
    // 只处理数据行
    if (e.Row.RowType != DataControlRowType.DataRow) return;
    var item = (Objects)e.Row.DataItem;
    if (item.Type == ClassType.Negative)
    {
        // 替换为你的Quantity列对应的索引或者控件查找逻辑
        e.Row.Cells[3].Text = (-item.Quantity).ToString();
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 04:42:04