How to make a list of string pairs ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

How to make a list of string pairs ?

I want to list some string pairs. The are not key / value pairs but two strings that belong together I have lots of those pairs and want to put them in a list. I need to loop through the list. And be able to print either on of them or both. How to do that ? In my opnion it is not a dictionairy, because the key is not unique. and a list <string,string> is not allowed. https://code.sololearn.com/cA16a1a81a3A/?ref=app

11th Jun 2021, 8:17 AM
sneeze
sneeze - avatar
5 Answers
+ 4
sneeze I've cleaned up my code a little. It was after 3am EDT when I wrote it and I later realized I didn't save my last set of changes before crashing for the night. Here's the simple versions to review. Let me know which you prefer and why. var array2d = new string[,] { {"a", "b"}, {"c", "d"} }; var jaggedArray = new string[][] { new string[] {"c", "z"}, new string[] {"z", "b"} }; var listofArrays = new List<string[]> { new[] {"c", "d"}, new[] {"c", "z"} }; var nestedLists = new List<List<string>> { new List<string> {"a", "b"}, new List<string> {"a", "x"} }; var listOfTuples = new List<(string s1, string s2)> { (s1: "a", s2: "b"), (s1: "z", s2: "b") }; You can review how I enumerate these in the Print extension methods found in the code. These do require very different approaches. So you may want to review those methods. https://code.sololearn.com/cZudM0s2KIbK/?ref=app
12th Jun 2021, 4:27 PM
David Carroll
David Carroll - avatar
+ 3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SoloLearn { class Program { static void Main(string[] args) { var myList = new List<Tuple<string, string>>(); myList.Add(Tuple.Create("a", "b")); myList.Add(Tuple.Create("c", "d")); } } } // something like above works. Note you can also dictionary to achieve what you wanted. ALSO, there is a typo in your code - myList src:- https://stackoverflow.com/questions/7095820/what-is-the-best-way-to-store-pairs-of-strings-make-an-object-or-use-a-class-in
11th Jun 2021, 8:39 AM
Rohit
+ 3
sneeze Here are a handful of ways to do what you want. https://code.sololearn.com/cZudM0s2KIbK/?ref=app
12th Jun 2021, 9:19 AM
David Carroll
David Carroll - avatar
+ 2
rkk How do you print the elements of the tuple?
11th Jun 2021, 8:40 AM
sneeze
sneeze - avatar
+ 2
// [CODE: To print tuple] using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SoloLearn { class Program { static void Main(string[] args) { var myList = new List<Tuple<string, string>>(); myList.Add(Tuple.Create("a", "b")); myList.Add(Tuple.Create("c", "d")); foreach (var tuple in myList) { Console.WriteLine("{0}, {1}", tuple.Item1, tuple.Item2); } } } }
11th Jun 2021, 8:47 AM
Rohit