I want to do a query with linq (list of objects) and I really don't know how to do it, I can do the group and the sum but can't select rest of the fields. Example:

ID  Value     Name   Category
1   5         Name1  Category1  
1   7         Name1  Category1
2   1         Name2  Category2
3   6         Name3  Category3
3   2         Name3  Category3

I want to group by ID, SUM by Value and return all fields like this.

ID  Value     Name   Category
1   12        Name1  Category1  
2   1         Name2  Category2
3   8         Name3  Category3

推荐答案

Updated : If you're trying to avoid grouping for all the fields, you can group just by Id:

data.GroupBy(d => d.Id)
    .Select(
        g => new
        {
            Key = g.Key,
            Value = g.Sum(s => s.Value),
            Name = g.First().Name,
            Category = g.First().Category 
        });

But this code assumes that for each Id, the same Name and Category apply. If so, you should consider normalizing as @Aron suggests. It would imply keeping Id and Value in one class and moving Name, Category (and whichever other fields would be the same for the same Id) to another class, while also having the Id for reference. The normalization process reduces data redundancy and dependency.

Asp.net相关问答推荐

目前不支持超过 65534 个段的跨区存档

在这个 For 循环计数没有增加

为什么 Web 架构应该是松耦合的?

在 lambda 表达式中否定 Func

ASP.NET web api 无法获取 application/x-www-form-urlencoded HTTP POST

如何防止 Azure 网站进入Hibernate 状态?

jquery 1.9.0 和 modernizr 无法使用 ASP.NET Web 优化框架进行缩小

HttpContext.Cache 过期

__doPostBack 未定义

MvcBuildViews true 与 ASP.NET MVC 2 中的实体框架

在 Asp.net Rowcommand 事件中获取行索引

LINQ:使用 Lambda 表达式获取 CheckBoxList 的所有选定值

Owin 中是否有来自 Global.asax 的 Application_End?

如何将表从存储过程检索到数据表?

模型是否包含字段而不将其添加到数据库中?

MSBuild DeployOnBuild=true 不发布

在 Application_BeginRequest 中设置会话变量

RegisterStartupScript 不适用于 ScriptManager、Updatepanel.这是为什么?

您将如何将 ASP.Net MVC 嵌入到现有的网站项目中?

ASP.NET 自定义控件 - 未知的服务器标记