C # - How to extract a list of one specific member of an array from a list of arrays

Given a list of arrays, I would like to extract the second element from each array in the list to a list of strings.

For example, let's say the list of arrays contains: {"1", "A", "X"} {"2", "B", "Y"} {"3", "C", "Z"}

what I would like the output to be is a list of lines containing: "A", "B" and "C"

so that I can say:

 List<string> myListOfStrings = new List<string>(); myListofStrings.AddRange(???) 
+6
source share
3 answers

If you know for sure that all arrays have an element at index 1, you can do this with LINQ on the same line:

 var myListOfStrings = listOfArrays.Select(a => a[1]).ToList(); 

Demo version

+12
source

You can simply create a new array and put the elements you need into it from your jagged array:

 List<string> myListOfStrings = (new[] {listOfArrays[0][1], listOfArrays[1][1]), listOfArrays[2][1]}).ToList(); 

Or do something like:

 List<string> myListOfStrings = new List<string>(); for(int i = 0; i < listOfArrays.Length; i++) myListOfStrings.Add(listOfArrays[i][1]); 

PS Specially for dasblinkenligh :

 class Program { static string[][] GetRandomJaggedArray(int numberOfArrays, int numberOfElements) { string[][] temp = new string[numberOfArrays][]; for (int i = 0; i < numberOfArrays; i++) { temp[i] = new string[numberOfElements]; for (int i2 = 0; i2 < temp.Length; i2++) temp[i][i2] = Guid.NewGuid().ToString(); } return temp; } static TimeSpan getElementsAtIndexLINQ(string[][] listOfArrays, int index, int count) { Stopwatch s = new Stopwatch(); List<string> myListOfStrings; s.Start(); for (int i = 0; i < count; i++) myListOfStrings = listOfArrays.Select(a => a[index]).ToList(); s.Stop(); return s.Elapsed; } static TimeSpan getElementsAtIndexFOR(string[][] listOfArrays, int index, int count) { Stopwatch s = new Stopwatch(); List<string> myListOfStrings = new List<string>(); s.Start(); for (int i2 = 0; i2 < count; i2++ ) for (int i = 0; i < listOfArrays.Length; i++) myListOfStrings.Add(listOfArrays[i][index]); s.Stop(); return s.Elapsed; } static void Main(string[] args) { string[][] test1 = GetRandomJaggedArray(100, 1000); string[][] test2 = GetRandomJaggedArray(100, 1000); TimeSpan t1 = getElementsAtIndexLINQ(test1, 1, 10); TimeSpan t2 = getElementsAtIndexFOR(test2, 1, 10); Console.WriteLine("Linq method took {0} ticks to execute", t1.Ticks); Console.WriteLine("For method took {0} ticks to execute", t2.Ticks); Console.ReadKey(); } } 

Output:

enter image description here

Read more about LINQ vs FOR here: Compare with Linq - Performance versus the Future

+2
source

If you do not want to use LINQ - try ...

 foreach( Array arItems in listOfArrays ) myListOfStrings.Add( arItem[ 1 ] ); 
+1
source

All Articles