交织一系列电子邮件地址,避免具有相同域的项连续 [英] Interleave an array of email addresses avoiding items with same domain to be consecutive

查看:134
本文介绍了交织一系列电子邮件地址,避免具有相同域的项连续的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种有效的方法来对一组电子邮件地址进行排序,以避免在C#中具有相同域的项是连续的。

I'm looking for an efficient way of sorting an array of email addresses to avoid items with the same domain to be consecutive, in C#.

内部的电子邮件地址

示例:

给出一个包含以下内容的数组:以下条目:

Given an array with the following entries:

john.doe@domain1.com
jane_doe@domain1.com
patricksmith@domain2.com
erick.brown@domain3.com

我想获得类似于以下内容:

I would like to obtain something similar to the following:

john.doe@domain1.com    
patricksmith@domain2.com
jane_doe@domain1.com
erick.brown@domain3.com


推荐答案

借助扩展方法(从 https://stackoverflow.com/a/27533369/172769 窃取) ,您可以这样操作:

With the help of an extension method (stolen from https://stackoverflow.com/a/27533369/172769), you can go like this:

List<string> emails = new List<string>();
emails.Add("john.doe@domain1.com");
emails.Add("jane_doe@domain1.com");
emails.Add("patricksmith@domain2.com");
emails.Add("erick.brown@domain3.com");

var q = emails.GroupBy(m => m.Split('@')[1]).Select(g => new List<string>(g)).Interleave();

Interleave 方法的定义为:

public static IEnumerable<T> Interleave<T>(this IEnumerable<IEnumerable<T>> source )
{
    var queues = source.Select(x => new Queue<T>(x)).ToList();
    while (queues.Any(x => x.Any())) {
        foreach (var queue in queues.Where(x => x.Any())) {
            yield return queue.Dequeue();
        }
    }
}

基本上,我们创建了组根据电子邮件地址的域部分,将每个组投影(或选择)到 List< string> ,然后交织这些列表。

So basically, we create groups based on the domain part of the email adresses, project (or Select) each group into a List<string>, and then "Interleave" those lists.

我已经对您的样本数据进行了测试,但是可能需要更彻底的测试才能发现边缘情况。

I have tested against your sample data, but more thorough testing might be needed to find edge cases.

DotNetFiddle代码段

欢呼声

这篇关于交织一系列电子邮件地址,避免具有相同域的项连续的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆