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相关问答推荐

在 Web.Config 中模拟标签

如何在现有数据库中创建 ASP.Net Identity 表?

如何使用 executeReader() 方法仅检索一个单元格的值

Web API Queryable - 如何应用 AutoMapper?

Azure Service Fabric 是否与 Docker 做同样的事情?

如何在没有实体框架的情况下使用 ASP.NET Identity 3.0

为什么默认情况下不允许 GET 请求返回 JSON?

ASP.NET IIS - 请求何时排队?

如何将 Web 应用程序项目转换为类库项目

最佳服务器端 .NET PDF 编辑库

错误:无法在 Web 服务器上开始调试... ASP.NET 4.0

在asp.net mvc 3中实现FilterAttribute,IActionFilter和从ActionFilterAttribute继承有什么区别?

在 ASP.NET 4.5 WebForms 中通过 bundle.config 与 BundleConfig.cs Bundle 资源

MVC5 身份验证中的......与主域之间的信任关系失败

对 ASP.NET 2.0 网页进行单元测试的最佳方法是什么?

禁用 web.config 继承?

缩小 ASP.Net MVC 应用程序的 HTML 输出

.NET 4.0 中的自定义 MembershipProvider

远程计算机无法连接到 Visual Studio Web 服务器

为什么 Controls 集合不提供所有 IEnumerable 方法?