欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

动态linq,实现查询动态字段

程序员文章站 2022-03-05 09:27:23
...
        /// <summary>
        /// 综保电量统计
        /// </summary>
        /// <param name="mod">时间维度:Y年、M月、D日、T时间段</param>
        /// <param name="time">时间</param>
        /// <returns>该时间内各回路电量使用情况</returns>
        public async Task<dynamic> GetRealyEnergyStat(string mod, DateTime time)
        {
            using (PDMDBContext db = new PDMDBContext())
            {
                var realyList = db.RelayDevice.Select(m => new { m.Name, m.ID }).Distinct().ToList();

                var queryWhere = db.RealyDayEnergyStat
                                .Where(m => mod == "Y" ? m.RcdTime.Year == time.Year :
                                            mod == "M" ? m.RcdTime.ToString("yyyy/MM") == time.ToString("yyyy/MM") :
                                            mod == "D" ? m.RcdTime.ToString("yyyy/MM/dd") == time.ToString("yyyy/MM/dd") :
                                            true);

                var query = from r in queryWhere
                            group r by new
                            {
                                RcdTime = mod == "Y" ? r.RcdTime.ToString("yyyy/MM") :
                                          mod == "M" ? r.RcdTime.ToString("yyyy/MM/dd") :
                                          mod == "D" ? r.RcdTime.ToString("yyyy/MM/dd HH") :
                                          r.RcdTime.ToString("yyyy/MM/dd HH:mm:ss")
                            } into g
                            select g;

                StringBuilder param = new StringBuilder();
                foreach (var item in realyList)
                {
                    param.Append($", Where(RelayDevIDFK == {item.ID}).Sum(Wp) AS Wp{item.ID}");
                }

                var result = await query.Select($"new (Key.RcdTime {param.ToString()})").ToDynamicListAsync();

                var resultSum = await queryWhere.GroupBy(m => m.RcdTime != null).Select($"new ({param.ToString().TrimStart(',')})").ToDynamicListAsync();

                return new { realyList, result, resultSum };
            }
        }

需要引入System.Linq.Dynamic.Core

相关标签: linq