Max Rowe
Max Rowe

Reputation: 91

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

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?

Upvotes: 5

Views: 10165

Answers (2)

DavidG
DavidG

Reputation: 119186

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));

Upvotes: 5

Markus
Markus

Reputation: 22511

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();

Upvotes: 13

Related Questions