【发布时间】:2018-03-04 02:38:35
【问题描述】:
假设我有一个名为 TestRecords 的数据库表,模型如下所示:
public class TestRecords
{
public int Id {get;set;}
public Date DateEntered {get;set;}
public int SecId {get;set;}
public int PhoneCallsTaken {get;set;}
}
现在,我有一个如下所示的主视图模型:
public class MyMainViewModel
{
public string Location {get;set;}
public IEnumerable<MyChildViewModel> Children {get;set;}
}
还有我的子视图模型:
public class MyChildViewModel
{
public string Month { get; set; }
public string Year { get; set; }
public double TotalPhoneCalls { get; set; }
}
假设在数据库中有TestRecords 表中的记录。
TestRecords
ID | DateEntered | SecId | PhoneCallsTaken
-------------------------------------------------------------
1 8/1/2017 2 35
2 8/2/2017 2 30
5 9/1/2017 2 30
我希望我的结果是:
我想按SecId 对这些记录进行分组,我知道这只是db.TestRecords.GroupBy(x => x.SecId).. 这不是我的困惑。
这是我期望的结果,SecId 等于 2
2
Month | Year | PhoneCallsTaken
------------------------------------------
August 2017 65
September 2017 30
这是我收到的:
2
Month | Year | Total Phone Calls
------------------------------------------
August 2017 65
August 2017 65
September 2017 30
它重复了 8 月总计,因为数据库中有 2 条记录,其中 SecId 等于 2,月份是 8 月。
这是我的 C# 代码:
var data = db.TestRecords.ToList();
IEnumerable<MyMainViewModel> model = data.GroupBy(x => x.Section.SectionName)
.Select(y => new MyMainViewModel()
{
Location = y.Key,
Children = y.Select(z => new MyChildViewModel()
{
Month = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(z.DateEntered.Month),
Year = z.DateEntered.Year.ToString(),
TotalPhoneCalls = y.Where(t => t.Section.SectionName == z.Section.SectionName)
.Sum(t => t.PhoneCallsTaken)
}).Distinct()
});
我怎样才能使在同一月份/年份输入的记录不同?
感谢任何帮助。
【问题讨论】:
-
按具有这两个属性的匿名对象分组。
-
带有样本输入和预期输出的stackoverflow.com/help/mcve 会很棒。
-
您需要创建一个临时对象,其中仅包含您想要返回的字段。您当前的设计在执行 GroupBy 时包含对象的所有属性,如果您在 sql 中执行相同的语句,您将收到与您得到的类似结果
-
@Nkosi 你是什么意思?你能提供一个视觉解释吗?
标签: c# linq group-by asp.net-mvc-5