加入两个不同长度的列表 [英] Join two lists of different length

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

问题描述

我正在使用LINQ:

List<String> listA = new List<string>{"a", "b", "c", "d", "e", "f", "g"};  
List<String> listB = new List<string>{"1", "2", "3"};  

所需结果:

{"a", "1", "b", "2", "c", "3", "d", "1", "e", "2", "f", "3", "g", "1"}  

我尝试但失败了:

var mix = ListA.Zip(ListB, (l1, l2) => new[] { l1, l2 }).SelectMany(x => x);  
//Result : {"a", "1", "b", "2", "c", "3"}  

var mix = ListA.Zip(ListB, (a, b) => new[] { a, b })
        .SelectMany(x => x)
        .Concat(ListA.Count() < ListB.Count() ? ListB.Skip(ListA.Count()) : ListA.Skip(ListB.Count()))
        .ToList();  
//Result : {"a", "1", "b", "2", "c", "3", "d", "e", "f", "g"}  

如何使用LINQ做到这一点?

How can I do this using LINQ?

推荐答案

即使我不确定为什么您需要它作为linq表达式,此方法仍然有效:

This works, even if I am not sure why you need it as linq expression:

var mix = Enumerable
           .Range(0, Math.Max(listA.Count, listB.Count))
           .Select(i => new[] { listA[i % listA.Count], listB[i % listB.Count] })
           .SelectMany(x => x);

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

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