4

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?

Max Rowe
  • 81
  • 2
  • 7
  • 1
    `(string list1, object list2)` is a ValueTuple struct, not a Tuple class. If you want value tuples (which I would recommend due to the tuple components being properly named) just replace `new Tuple(x, y)` or `Tuple.Create(a, b)` in the answers by `(x, y)` or `(a, b)`, respectively. – ckuri Feb 14 '19 at 12:44
  • can you show me an example please? – Max Rowe Feb 14 '19 at 15:47
  • If you take Markus answer just replace the last line with `List<(string yourFieldNameHere1, object yourFieldNameHere)> result = lst.Zip(obj, (x, y) => (x, y)).ToList();` – ckuri Feb 14 '19 at 15:48

2 Answers2

11

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();
Markus
  • 20,838
  • 4
  • 31
  • 55
  • This will merge two list. Is it OP's expected behavior? Not sure form his question. – TanvirArjel Feb 14 '19 at 12:43
  • @TanvirArjel from the title: "How do I get two lists into one..."; I suspect the pseudo-code in the question is a bit misleading. – Markus Feb 14 '19 at 12:46
  • Yes! Your are correct what you have understood! it can also be he is trying pass two list as tuple like (list1,list2). But using Zip do parallel looping through the items, not serially. – TanvirArjel Feb 14 '19 at 12:49
5

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));
DavidG
  • 113,891
  • 12
  • 217
  • 223