c# - 有没有更有效的方法来对这些字典进行排序
问题描述
所以我查询了一个数据库来创建一个名为“活动”的集合,这些调用具有相关的问题和相关的日期。如果活动日期是 0-3 个月、4-12 个月或超过一年,我需要返回前 3 个问题。我创建了一个算法,但出于学习目的,我认为可能有更好的方法来有效地对这些活动进行分类。这是我的代码
var activities = ctx.Activities.Where(a => a.SiteID == propID && a.ActivityTypeName == "Call" && a.ParcelData.Parcel_LetterTracking.LMailDate != null)
.Select(x => new
{
callDate = x.DateTimeEntry,
mailDate = x.Contact.OwnerContact.ParcelDatas.FirstOrDefault(a => a.OwnerContactID == x.Contact.OwnerContact.OOwnerID).Parcel_LetterTracking.LMailDate,
question = x.FAQs.FirstOrDefault(a => a.ActivityID == x.ActivityID).FAQ_Library.FaqNum + " - " +
x.FAQs.FirstOrDefault(a => a.ActivityID == x.ActivityID).FAQ_Library.Question
}).AsEnumerable();
// create a dictionary of Key = the question and Value = the count of occurences in activities for each time frame.
Dictionary<string, int> calls3month = new Dictionary<string, int>();
Dictionary<string, int> calls6month = new Dictionary<string, int>();
Dictionary<string, int> calls12month = new Dictionary<string, int>();
// counters for number of calls between each range
int numberOfCalls3Months = 0;
int numberOfCalls4to6Months = 0;
int numberOfCalls12Months = 0;
foreach (var call in activities)
{
// if calldate - maildate is 3 months, 4-12 months or 12+ months
TimeSpan deltaOfDates = call.callDate.Subtract((DateTime)call.mailDate);
if (deltaOfDates.Days < 91 && deltaOfDates.Days > 0)
{
if (calls3month.TryGetValue(call.question, out int count))
{
calls3month[call.question] = count + 1;
}
else {
calls3month.Add(call.question, 1);
}
numberOfCalls3Months++;
}
else if (deltaOfDates.Days < 365 && deltaOfDates.Days >= 91)
{
if (calls6month.TryGetValue(call.question, out int count))
{
calls6month[call.question] = count + 1;
}
else
{
calls6month.Add(call.question, 1);
}
numberOfCalls4to6Months++;
}
else if (deltaOfDates.Days >= 365)
{
if (calls12month.TryGetValue(call.question, out int count))
{
calls12month[call.question] = count + 1;
}
else
{
calls12month.Add(call.question, 1);
}
numberOfCalls12Months++;
}
}
//grab top 3 questions asked. Key = the question, value = the frequency
var topCalls3month = calls3month.OrderByDescending(kvp => kvp.Value).Take(3).ToArray();
var topCalls6month = calls6month.OrderByDescending(kvp => kvp.Value).Take(3).ToArray();
var topCalls12month = calls12month.OrderByDescending(kvp => kvp.Value).Take(3).ToArray();
当我枚举活动集合时,对这些进行排序会更快吗?If(dictionary.value is in the top 3 将其添加到列表顶部) 我可以使用什么策略来做到这一点?
最后,当我使用 orderbyDescending 时,我觉得这效率低下,应该从 foreach 循环中对字典进行排序/
解决方案
推荐阅读
- python - 附加类作为方法
- machine-learning - 哪种归一化方法,最小-最大或 z-scaling(零均值单位方差)最适合深度学习?
- r - 拆分列表并在 R 中保留第一个值
- git - 在 CodeBuild 中获取从本地分支到当前分支的更改?
- c# - 将面板停靠在 winform DockStyle.Right 的右侧,但还要指定高度
- python-3.x - 文本 tada 的 dict/list 理解性能
- c# - 如何检测泛型抽象类的子类?
- google-sheets - 基于 [日期]+X 的 Google 表格中的条件格式单元格
- mongodb - 你建立的最大的 mongo 分片集群是什么?
- node.js - Fabric 网络和 Node.js 客户端应用程序之间的连接