我正在寻找一种有效的方法来对电子邮件地址数组进行排序,以防止在C#中具有相同域的项是连续的。
数组中的电子邮件地址已经是不同的,并且全部为小写。
例子:
给定一个包含以下条目的数组:
[email protected]
[email protected]
[email protected]
[email protected]
我想获得类似于以下内容的东西:
[email protected]
[email protected]
[email protected]
[email protected]
借助扩展方法(从https://stackoverflow.com/a/27533369/172769窃取),您可以像这样:
List<string> emails = new List<string>();
emails.Add("[email protected]");
emails.Add("[email protected]");
emails.Add("[email protected]");
emails.Add("[email protected]");
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>
,然后“交织”这些列表。
我已经针对您的样本数据进行了测试,但是可能需要进行更彻底的测试才能发现边缘情况。
干杯
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句