2017-02-11 3 views
0

У меня есть проблема получения значений в порядке, что я хочу я написал простой код, чтобы продемонстрировать:Как получить первый, второй ... значения двух строковых списков внутри списка массивов?

List<string> st1 = new List<string>() {"st11","st12"}; 
List<string> st2 = new List<string>() {"st21","st22"}; 
ArrayList stringArrayList = new ArrayList(); 
stringArrayList.Add(st1); 
stringArrayList.Add(st2); 

string[] n1 = new string[10]; 
int i = 0; 
foreach (List<string> item in stringArrayList) 
{ 
    foreach (var item2 in item) 
    { 
     n1[i] = item2; 
     i++; 
    } 
} 

в этом коде на выходе будет: ST11, ST12 ST21, S22

я хочу это, чтобы получить значения, как это: ST11, ST21 ST12, ST22

я хочу информацию, хранящуюся в этом порядке «ST11, ST21 ST12, ST22» в n1

+0

Что бы вы хотели, если списки имеют разную длину? – NineBerry

+0

в моем случае не имеют разной длины –

ответ

3

Если длина списка такие же вы можете делать что-то повесят, как это:

int j = 0; 
int lengthToLoop = st1.length; 
for(int i = 0; i < lengthToLoop; i++) 
{ 
    n1[j++] = st1[i]; 
    n1[j++] = st2[i]; 
} 

Если длина не равна вы можете вычислить минимум, скопировать минимальную длину элемента от каждого, а затем скопировать остальные.

1

Сначала проверьте максимальную длину списка, а затем возьмите элемент с индексом (0,1,3 ... до макс.) Из каждого списка. Не забудьте проверить, существует ли индекс. Кроме того, вы можете установить точный размер n1, потому что это сумма всех списков. В этом случае вам не нужно иметь выделенную линию для i++.

 List<string> st1 = new List<string> { "st11", "st12" }; 
     List<string> st2 = new List<string> { "st21", "st22" }; 
     List<List<string>> stringArrayList = new List<List<string>> {st1, st2}; 
     int maxCount = stringArrayList.Max(x => x.Count); 
     int totalItems = 0; 
     stringArrayList.ForEach(x=> totalItems+= x.Count); 
     string[] n1 = new string[totalItems]; 
     int i = 0; 

     for (int index = 0; index < maxCount; index++) 
     { 
      foreach (var list in stringArrayList) 
      { 
       if (list.Count > index) 
       { 
        n1[i++] = list[index];      
       } 
      } 
     } 
1

Вы должны отменить две петли, сделав внешний контур внутренней петлей.

Используйте цикл for вместо цикла foreach для внешнего цикла, используя длину строковых массивов в качестве разделителя.

Также: Не используйте ArrayList, а настоящий типизированный список.

List<string> st1 = new List<string>() { "st11", "st12" }; 
List<string> st2 = new List<string>() { "st21", "st22" }; 

List<List<string>> stringArrayList = new List<List<string>>(); 
stringArrayList.Add(st1); 
stringArrayList.Add(st2); 

// Get length of first string array 
int firstArrayLength = stringArrayList[0].Count; 

string[] n1 = new string[10]; 
int i = 0; 

// For each position in the arrays from 0 to firstArrayLength -1 do 
for (int arrayPosition = 0; arrayPosition < firstArrayLength; arrayPosition++) 
{ 
    // For each of the string array 
    foreach (var stringArray in stringArrayList) 
    { 
     // Get the item from the stringArray at position arrayPosition 
     n1[i] = stringArray[arrayPosition]; 
     i++; 
    } 
} 
2

Вот реализация, которая будет делать то, что вы ищете, а также будет обрабатывать зубчатые массивы.

List<string> st1 = new List<string>() { "st11", "st12" }; 
List<string> st2 = new List<string>() { "st21", "st22", }; 
ArrayList stringArrayList = new ArrayList(); 
stringArrayList.Add(st1); 
stringArrayList.Add(st2); 

//this will protect us against differing max indexes if the 2D array is jagged. 
int maxIndex = 0; 
int totalElements = 0; 
foreach (List<string> currentList in stringArrayList) 
{ 
    if (currentList.Count > maxIndex) 
    { 
     maxIndex = currentList.Count; 
    } 
    totalElements += currentList.Count; 
} 

string[] n1 = new string[totalElements]; 
int i = 0; 
for (int j = 0; j < maxIndex; j++) 
{ 
    for (int k = 0; k < stringArrayList.Count; k++) 
    { 
     List<string> currentStringArray = (List<string>)stringArrayList[k]; 
     if (j < currentStringArray.Count) 
     { 
      n1[i] = currentStringArray[j]; 
      i++; 
     } 

    } 
} 
Смежные вопросы