如何在C#中将两个列合并为两列 [英] How to merge two list as two columns in C#

查看:207
本文介绍了如何在C#中将两个列合并为两列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我有两个列表,在新列表中,我想将这两个列合并为两列,在c#中。



我尝试了什么:



i尝试过使用联系方式,但它只在一列中添加列表。



请帮助我们。



谢谢

Hi Guys,

I have two lists and in new list i want to merge these two as two columns, in c#.

What I have tried:

i have tried using contact but it is add list in one column only.

plz help me guys.

Thanks

推荐答案

这很复杂,因为它取决于两个列表中的内容。如果它们有共同的价值,你可以很容易地加入它们,但我怀疑你希望将它们组合成一个新列表中的两列,而不是它们。

在这种情况下,它是一个有点复杂,但是:

That's complicated, because it depends on what is in the two lists. If they share a common value, you can JOIN them fairly easily, but I suspect from your wish to combine them as two columns in a new list that they don't.
In that case, it's a bit complicated, but:
List<string> ls = new List<string>();
ls.Add("S1");
ls.Add("S2");
ls.Add("S3");
ls.Add("S4");
List<int> li = new List<int>();
li.Add(1);
li.Add(2);
li.Add(3);
li.Add(4);
var newList = ls.Join(li, s => ls.IndexOf(s), i => li.IndexOf(i), (s, i) => new { sv = s, iv = i }).ToList();
foreach (var x in newList)
    {
    Console.WriteLine("{0}, {1}", x.sv, x.iv);
    }



将为您提供您想要的两列:


Will give you the two columns you seem to want:

S1, 1
S2, 2
S3, 3
S4, 4


看起来你可以使用Linq的 .Zip()

It looks like you could just use Linq's .Zip():
// "borrowing" from OriginalGriff's code ;-)
List<string> ls = new List<string>();
ls.Add("S1");
ls.Add("S2");
ls.Add("S3");
ls.Add("S4");
List<int> li = new List<int>();
li.Add(1);
li.Add(2);
li.Add(3);
li.Add(4);
var newList = ls.Zip(li, (s, i) => new { sv = s, iv = i }).ToList();
foreach (var x in newList)
{
  Console.WriteLine("{0}, {1}", x.sv, x.iv);
}



如果列表长度不同, .Zip()将在耗尽。


这篇关于如何在C#中将两个列合并为两列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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