【发布时间】:2013-10-01 22:40:18
【问题描述】:
我在数据库中有一个包含 2 个字段的表:索引 (int)、电子邮件(varchar(100))
我需要做以下事情:
- 按域名对所有电子邮件进行分组(所有电子邮件都已小写)。
- 从所有组中选择所有电子邮件,其中域的电子邮件总和不超过步骤 1 之前电子邮件总数的 20%。
代码示例:
DataContext db = new DataContext();
//Domains to group by
List<string> domains = new List<string>() { "gmail.com", "yahoo.com", "hotmail.com" };
Dictionary<string, List<string>> emailGroups = new Dictionary<string, List<string>>();
//Init dictionary
foreach (string thisDomain in domains)
{
emailGroups.Add(thisDomain, new List<string>());
}
//Get distinct emails
var emails = db.Clients.Select(x => x.Email).Distinct();
//Total emails
int totalEmails = emails.Count();
//One percent of total emails
int onePercent = totalEmails / 100;
//Run on each email
foreach (var thisEmail in emails)
{
//Run on each domain
foreach (string thisDomain in emailGroups.Keys)
{
//If email from this domain
if (thisEmail.Contains(thisDomain))
{
//Add to dictionary
emailGroups[thisDomain].Add(thisEmail);
}
}
}
//Will store the final result
List<string> finalEmails = new List<string>();
//Run on each domain
foreach (string thisDomain in emailGroups.Keys)
{
//Get percent of emails in group
int thisDomainPercents = emailGroups[thisDomain].Count / onePercent;
//More than 20%
if (thisDomainPercents > 20)
{
//Take only 20% and join to the final result
finalEmails = finalEmails.Union(emailGroups[thisDomain].Take(20 * onePercent)).ToList();
}
else
{
//Join all to the final result
finalEmails = finalEmails.Union(emailGroups[thisDomain]).ToList();
}
}
有人知道更好的制作方法吗?
【问题讨论】:
-
看起来您只是想以某种方式过滤所有结果,而分组只是实现这一目标的垫脚石?顺便说一句,您能否更清楚地说明为什么
101,102而不是100,101,104,105相同但不是103,104?从下往上收集物品? -
您能否确认是否要完全排除某个域,如果它的总数超过总数,或者您是否想要包含所有达到阈值的电子邮件?
-
我只需要把所有的邮件都拿到门槛
-
@KonstantinFedoseev 你检查过我的解决方案了吗?如果它不起作用,请留下一些评论让我知道,我想知道它是如何不起作用的。