C#中的排序列表以合并每个列表的项目

马科斯·保罗·阿马拉尔

我有一个按主机名分组的电子邮件列表。我需要以交错的方式加入这些电子邮件,然后发送它们。

public List<string> ReturnOrder()
{ 
    List<string> listMerge = new List<string>();
    List<List<string>> listEmail = new List<List<string>>();
    listEmail.Add(new List<string> { "[email protected]", "[email protected]", "[email protected]" });            
    listEmail.Add(new List<string> { "[email protected]", "[email protected]" });
    listEmail.Add(new List<string> { "[email protected]", "[email protected]", "[email protected]", "[email protected]"});
    return listMerge;
}
//顺序:
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected]

我需要得到以下结果,我做了几次不成功的尝试

RJ

一个简单的实现将是这样的:

        List<string> listMerge = new List<string>();
        List<List<string>> listEmail = new List<List<string>>();
        listEmail.Add(new List<string> { "[email protected]", "[email protected]", "[email protected]" });
        listEmail.Add(new List<string> { "[email protected]", "[email protected]" });
        listEmail.Add(new List<string> { "[email protected]", "[email protected]", "[email protected]", "[email protected]" });

        for(int i =0; i < listEmail.Select(x => x.Count).Max(); i++)
        {
            for(int j = 0; j < listEmail.Count; j++)
            {
                if (listEmail[j].Count <= i)
                    continue;

                listMerge.Add(listEmail[j][i]);
            }
        }

每次外循环结束时,都会消耗所有列表中的一项。因此,外部循环运行的迭代次数等于最长列表。

内循环遍历每个列表并选择一项(如果指定索引存在一项。)

这可能会变得更有效率,但就您的目的而言,这应该足够了。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章