c#-GroupBy模拟

概念说明

定义:GROUP BY 语句用于结合合计函数,根据一个或多个列对结果集进行分组。

解释:GROUP BY我们可以先从字面上来理解,GROUP表示分组,BY后面写字段名,就表示根据哪个字段进行分组。GROUP BY必须得配合聚合函数来用,分组之后你可以计数(COUNT),求和(SUM),求平均数(AVG)等。

白话:就是在一个选定条件形成的表中,将GROUP BY的字段重复的消除,并对该分类下的其他数据进行统计运算,就是分组后的多行都变成一行。GROUP BY 是个分组的条件,分组后,没一组只能表示出一条数据,这条数据用统计条件统计该分组的数据。

代码模拟

注:这里仅仅模拟GROUP BY的一种情况(GROUP BY + sum)

 

using System;
using System.Collections.Generic;

namespace GroupBy模拟2
{
    class Program
    {
        static string jishu = "奇数";
        static string oushu = "偶数";
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            Program p = new Program();
            p.main();
            Console.ReadLine();
        }
        private void main()
        {
            Table[] tables = new Table[10];
            for(int i = 0; i < 10; i++)
            {
                tables[i] = new Table();
                if (i % 2 == 0)
                {
                    tables[i].name = jishu;
                }
                else
                {
                    tables[i].name = oushu;
                }
            }
            for(int i = 0; i < 10; i++)
            {
                tables[i].display();
            }

            List<Table> tables2 = GROUP_BY(tables);
            Console.WriteLine("GROUP BY 后的输出");
            foreach(Table table in tables2)
            {
                table.display();
            }
        }
        private List<Table> GROUP_BY(Table[] tables)
        {
            List<Table> tables2 = new List<Table>();
            for (int i = 0; i < 10; i++)
            {
                string name = tables[i].name;
                Table seletTb = tables2.Find(x => x.name.Equals(name));
                if (null == seletTb)
                {
                    Table tb = new Table();
                    tb.name = name;
                    tb.sum++;
                    tables2.Add(tb);
                }
                else
                {
                    seletTb.sum++;
                }
            }
            return tables2;
        }
    }
    class Table
    {
        public string name;
        public int sum;
        public void display()
        {
            Console.WriteLine("name:" + name+ "  sum:" + sum);
        }
    }
}

相关引用

SQL中GROUP BY用法示例

SQL GROUP BY 语句

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值