合并多个列表 [英] Merging multiple lists

查看:194
本文介绍了合并多个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于目前我有一个列表的列表,列表<列表< T>> ,在其中所有列表包含0个或多个项目,有可能的,但不一定是所有相同的号码。而且我想寿都包含在列出所有的项目列表......但我希望以如下:首先关闭所有的列表中的第一个项目,以使他们出现在超级名单。

Given that there I have a list of lists, List<List<T>>, in which all lists contain 0 or more items, likely, but not necessarily all the same number. And I would like tho have a list containing all the items in the Lists... but I want the order to be as follows: first the first items off all the lists, in order that they appear in the 'super-list'.

例。

List[0] = { 'Apple', 'Blueberry', 'Cranberry' }
List[1] = { 'Anteater', 'Baboon', 'Camel', 'Dodo'}
List[2] = { 'Albatross', 'Blackbird', 'Chicken'}

result = { 'Apple', 'Anteater', 'Albatross', 'Blueberry', 'Baboon', 
           'Blackbird', 'Cranberry', 'Camel', 'Chicken', 'Dodo' }

(注意,这是不是按字母顺序排列,蓝莓来自狒狒之前)

(note that this is NOT alphabetical order, Blueberry comes before Baboon)

Ofcourse,我可以通过superlist用一个计数器只是循环,将项目添加到resultslist一个接一个,只要有一个名单,是不是空的:

Ofcourse, i could just loop through the 'superlist' with a counter, adding items to the resultslist one by one, as long as there is a list that isn't empty:

int i = 0;
bool done = false;

while (!done)
{
    bool found = false;

    foreach (list l in superlist)
    {
        if (l.Count() > i)
        {
           found = true;
           result.Add(l[i]);
        }
    }

    i++;

    if (!found)
        done = true;
}

不过,这将是更好的方式来使用一些优化的LINQ功能做到这一点。我一直在寻找到邮编,的 GROUPBY 和的总结,但不能让他们工作。

But it would be way nicer to use some optimized LINQ function to do this. I have been looking into Zip, GroupBy and Aggregate, but couldn't get them to work.

所以:是否有pretty的LINQ功能,或多种组合,将它变成pretty的code,或者我应该坚持由(也许优化)我目前的功能

So: Is there a pretty LINQ function, or combination of multiple, that would turn this into pretty code, or should I stick by (and maybe optimize) my current function?

编辑:一个简单的SelectMany(x => X)也不会做的伎俩,因为它preserves,而不是折叠他们列出的顺序,就像我的算法一样。请参阅我最初的问题的更多细节。

A simple SelectMany(x => x) also doesn't do the trick, as it preserves the order of the lists, instead of folding them, like my algorithm does. See my initial question for more details.

推荐答案

您需要的SelectMany

var result = lists.SelectMany(x => x.Select((s, inx) => new { s, inx }))
                .GroupBy(x => x.inx)
                .SelectMany(x => x.Select(y => y.s))
                .ToList();


修改

对于那些,谁想要尝试,初始化code。

For those, who want to try, the initialization code.

List<List<string>> lists = new List<List<string>>()
        {
            new List<string>(){ "Apple", "Blueberry", "Cranberry" },
            new List<string>(){ "Anteater", "Baboon", "Camel", "Dodo"},
            new List<string>(){ "Albatross", "Blackbird", "Chicken"},
        };

编辑2

输出: 苹果,食蚁兽,信天翁,蓝莓,狒狒,黑鸟,蔓越莓,骆驼,鸡,渡渡鸟

这篇关于合并多个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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