C#: How do i get 2 lists into one 2-tuple list in

混江龙づ霸主 提交于 2021-01-27 15:57:29

问题


I have 2 Lists. First one is Type string. The second is type object. Now I want to get both lists into a Tuple<string,object>. like this

var List = new(string list1, object list2)[]

How do I do this?

I had to create 2 seperate lists, because I am Serializing the object and the serializing wouldn't work if i had a List<Tuple<string,object>> in the first place. Both lists can get big so maybe with foreach loop?


回答1:


You can use the Zip method to create one list of the two:

var lst = new List<string>() { "a", "b" };
var obj = new List<object>() { 1, 2 };
var result = lst.Zip(obj, (x, y) => new Tuple<string, object>(x, y))
                .ToList();



回答2:


You can use the Linq Zip method:

List<string> list1 = GetStrings();
List<object> list2 = GetObjects();

var merged = list1.Zip(list2, (a, b) => Tuple.Create(a, b));


来源:https://stackoverflow.com/questions/54690401/c-how-do-i-get-2-lists-into-one-2-tuple-list-in

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!