gpt4 book ai didi

c# - GroupBy() 获取重复记录

转载 作者:行者123 更新时间:2023-11-30 23:08:40 24 4
gpt4 key购买 nike

假设我有一个名为 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;}
}

还有我的 subview 模型:

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

它重复八月总数,因为数据库中有 2 条记录,其中 SecId 等于 2,月份是八月。

这是我的 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()
});

如何让同月/同年输入的记录不同?

感谢任何帮助。

最佳答案

这是我在评论中提到的基本要点。

var model = data.GroupBy(_ => _.Section.SectionName)
.Select(section => new MyMainViewModel {
Location = section.Key,
Children = section.GroupBy(_ => new {
Month = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(_.DateEntered.Month),
Year = _.DateEntered.Year.ToString()
}).Select(period => new MyChildViewModel {
Month = period.Key.Month,
Year = period.Key.Year,
TotalPhoneCalls = period.Sum(_ => _.PhoneCallsTaken)
}).ToList()
});

您最初按部分分组。现在您还想按月和年对这些部分进行分组,然后对这些组的调用求和。

关于c# - GroupBy() 获取重复记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46366021/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com