如何获取不同项目及其计数的列表 [英] How to get a list of distinct items and their count

查看:125
本文介绍了如何获取不同项目及其计数的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用linq查询获取不同项目及其计数的列表并将其返回到mvc中的控制器



我的数据库表就像是

---------------------------

id name amount

1 a 10

1 a 20

2 b 30

2 b 40

2 b 50


i希望结果是

------------------------ ---

id名称金额

1 a 30

2 b 120



并将其返回给所有参数的mvc控制器



我尝试过:



如何使用linq查询获取不同项目及其计数的列表,并将其返回到mvc中的控制器

how to get a list of distinct items and their count using linq query and return it to the controller in mvc

my database table is like
---------------------------
id name amount
1 a 10
1 a 20
2 b 30
2 b 40
2 b 50

i want the result to be
---------------------------
id name amount
1 a 30
2 b 120

and return it to the mvc controller with all parameters

What I have tried:

how to get a list of distinct items and their count using linq query and return it to the controller in mvc

推荐答案

试试这个

try this
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
 
 
    class Class1
    {
        static void Main(string[] args)
        {
            List<MyEntity> lst = new List<MyEntity>();
            lst.Add(new MyEntity() { ID = 1, Name = "a", Amount = 10 });
            lst.Add(new MyEntity() { ID = 1, Name = "a", Amount = 20 });
            lst.Add(new MyEntity() { ID = 2, Name = "b", Amount = 30 });
            lst.Add(new MyEntity() { ID = 2, Name = "b", Amount = 40 });
            lst.Add(new MyEntity() { ID = 2, Name = "b", Amount = 50 });

            var lstOut = lst.GroupBy(k => new { k.ID, k.Name }).Select(x => new MyEntity() { ID = x.Key.ID, Name = x.Key.Name, Amount = x.ToList().Sum(k => k.Amount) }).ToList();
        }
    }
        

    class MyEntity
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public double Amount { get; set; }
    }


这篇关于如何获取不同项目及其计数的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆