合并具有可变长度“弹出"的多个列表.每个元素 [英] Merge multiple lists with variable length "popping" elements from each
本文介绍了合并具有可变长度“弹出"的多个列表.每个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将多个列表(它们的数量可变)排序到一个列表中,但要保持特定的顺序.例如:
I'd like to sort multiple lists (variable number of them) into single list, but keeping the specific order. For example:
List A: { 1,2,3,4,5 }
List B: { 6,7,8 }
List C: { 9,10,11,12 }
Result List: { 1,6,9,2,7,10,3,8,11,4,12,5 }
我唯一的想法是从每个列表中删除第一个元素并将其放入结果集中(并重复进行直到所有列表为空),但是也许有更好的方法不需要创建每个元素的副本列表,并且也不会影响原始列表吗?
The only idea I got was to remove the first element from each list and put it into resulting set (and repeat until all lists are empty), but maybe there is a better way that doesn't require to create copy of each list and doesn't affect the original lists as well?
推荐答案
更灵活的使用
public static string MergeArrays(params IList<int>[] items)
{
var result = new List<int>();
for (var i = 0; i < items.Max(x => x.Count); i++)
result.AddRange(from rowList in items where rowList.Count > i select rowList[i]);
return string.Join(",", result);
}
.
var a = new List<int>() { 1, 2, 3, 4, 5 };
var b = new List<int>() { 6, 7, 8 };
var c = new List<int>() { 9, 10, 11, 12, 0, 2, 1 };
var r = MergeArrays(a, b, c);
这篇关于合并具有可变长度“弹出"的多个列表.每个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文