2013-01-18 105 views
0
KeyValuePair<int, string>[][] partitioned = SplitVals(tsRequests.ToArray()); 

不要太担心我使用的方法;让我们只是说我得到了一个KeyValuePairs的锯齿阵列,这些阵列被平分为不同的阵列。将KeyValuePair <int,string>转换为int []数组和字符串[]数组

foreach (KeyValuePair<int, string>[] pair in partitioned) 
{ 
    foreach (KeyValuePair<int, string> k in pair) 
    { 
    } 
} 

我需要知道我怎样才能最有效地获得int数组的整数和字符串从keyvaluepairs的阵列一个单独的字符串数组。这样,两个索引都可以在单独的数组中匹配。

例如,在我将它分成一个int []数组和一个字符串[]数组,

intarray[3] must match stringarray[3] just like it did in the keyvaluepair. 

可以说我有与KVP交错数组等:

[1][]<1,"dog">, <2,"cat"> 
    [2][]<3,"mouse">,<4,"horse">,<5,"goat"> 
    [3][]<6,"cow"> 

我这需要在每次迭代

1. 1,2/"dog","cat" 
    2. 3,4,5/"mouse", "horse", "goat" 
    3. 6/"cow" 

回答

5
012变成
+0

所以我甚至不需要把th在循环内? – Ramie

+1

'SelectMany'和'Select'方法都会在内部循环提供给它们的序列,因此循环正在发生,您不需要自己编写它们。 – Servy

+0

你做了我想要的KVP,但不是我想要的整体。 第一个循环需要发生,无论它只是我想要避免的第二个循环。我基本上将我的keyvalpair数组分成更多的数组,但我不想把它们全部放在2个大列表中。每次循环时我都想将每个部分放在列表中。 – Ramie

0
List<int> keys = new List<int>(); 
List<string> values = new List<string>(); 
foreach (KeyValuePair<int, string>[] pair in partitioned) 
{ 
    foreach (KeyValuePair<int, string> k in pair) 
    { 
     keys.Add(k.Key); 
     values.Add(k.Value); 
    } 
} 
keyArray = keys.ToArray(); 
valueArray = values.ToArray(); 
0

只是为了让你开始:

var list = new List<KeyValuePair<int, int>>(); 
    var key = new int[list.Count]; 
    var values = new int[list.Count]; 
    for (int i=0; i < list.Count ;i++) 
    { 
     key[i] = list[i].Key; 
     values[i] = list[i].Value; 
    } 
0
public static void ToArrays<K,V>(this IEnumerable<KeyValuePair<K,V>> pairs, 
    out K[] keys, out V[] values) 
{ 
    var keyList = new List<K>(); 
    var valueList = new List<V>(); 
    foreach (KeyValuePair<K,V> pair in pairs) 
    { 
     keyList.Add(pair.Key); 
     valueList.Add(pair.Value); 
    } 
    keys = keyList.ToArray(); 
    values = valueList.ToArray(); 
} 

因为你有一个交错数组,你还需要压平使用该功能:

public static IEnumerable<T> flatten(this T[][] items) 
{ 
    foreach(T[] nested in items) 
    { 
     foreach(T item in nested) 
     { 
     yield return item; 
     } 
    } 
}  

整合所有像这样:

MyKeyValuePairCollection = GetKeyValuePairJaggedArray(); 
int[] keys; 
string[] values; 
MyKeyValuePairCollection.flatten().ToArrays(out keys, out values); 
+0

请注意,他有一组锯齿形的键值对。这不是'IEnumerable >'。这是一个'IEnumerable KeyValuePair >>'。 – Servy

+0

我仍然使用上面的功能,但有额外的代码来首先弄平锯齿;) –

+1

我的观点是这就是你想念的东西。您应该添加相关的功能来平整列表。 – Servy