我有两个列表,其中包含不同数量的项目。
(function() {
'use strict';
/**
* @ngdoc service
* @name gemStoreApp.productService
* @description
* # productService
*/
angular.module('gemStoreApp.productService',['ngResource'])
.factory('productsService', function($resource) {
return $resource('/products/:id', {id:'@id'},{
'update': { method: 'PUT'}
});
});
})();
现在我想从这些列表中得到最终结果。
__init__.py
如果列表被反转,如
a = {"a","b","c","d","e"}<br>
b = {"f","g","h"}
结果将是
a,f
b,g
c,h
d
e
我试图在互联网上搜索,但我的搜索总是会出现这种情况。
a = {"f","g","h"}
b = {"a","b","c","d","e"}
显示错误的结果
f,a
g,b
h,c
,d
,e
答案 0 :(得分:3)
我的更多选择
var c = Enumerable.Range(0, Math.Max(a.Length, b.Length))
.Select(i => (i < a.Length ? a[i] : "") + "," + (i < b.Length ? b[i] : ""))
.ToList();
或强>
var c = a.Select((s, i) => new { s, i })
.Concat(b.Select((s, i) => new { s, i }))
.GroupBy(x => x.i)
.Select(g => string.Join(",", g.Select(x => x.s)))
.ToList();
查看输出:
Console.WriteLine(String.Join(Environment.NewLine, c));
答案 1 :(得分:2)
对于两个列表的配对元素,您可以使用Enumerable.Zip
:
var a = new [] { "a", "b", "c", "d", "e"};
var b = new [] { "f", "g", "h" };
var c = a.Zip(b, (x, y) => x + "," + y);
您可以使用一些额外的逻辑来处理尾随元素:
if (a.Length > b.Length)
c = c.Concat(a.Skip(b.Length));
else if (b.Length > a.Length)
c = c.Concat(b.Skip(a.Length).Select(y => "," + y));
foreach (string z in c)
Console.WriteLine(z);
答案 2 :(得分:2)
这样的事情:
var a = new string[]{"a","b","c","d","e"};
var b = new string[]{"f","g","h"};
var l = Math.Max(a.Length, b.Length);
a = a.Concat(Enumerable.Repeat((string)null, l - a.Length)).ToArray();
b = b.Concat(Enumerable.Repeat((string)null, l - b.Length)).ToArray();
var c = a.Zip(b, (x,y) => x == null ? y : y == null ? x : x + "," + y);
首先使用空值填充两个数组,使它们的长度相同,然后将它们Zip
放在一起。结果:
a,f
b,g
c,h
d
e
在VB.Net中,它会像一样(无法弄清楚如何翻译VB中的(string)null
部分):
dim a = {"a","b","c","d","e"}
dim b = {"f","g","h"}
dim l = Math.Max(a.Length, b.Length)
a = a.Concat(Enumerable.Repeat("", l - a.Length)).ToArray()
b = b.Concat(Enumerable.Repeat("", l - b.Length)).ToArray()
dim c = a.Zip(b, Function(x,y) if (x = "", y, if (y = "", x , x + "," + y)))