KeyValuePair<int, string>[][] partitioned = SplitVals(tsRequests.ToArray());
不要太担心我使用的方法;我只想说我得到了一个被分割成不同数组的KeyValuePairs的锯齿状数组。
foreach (KeyValuePair<int, string>[] pair in partitioned)
{
foreach (KeyValuePair<int, string> k in pair)
{
}
}
我需要知道如何有效地获取int数组中的int,以及来自keyvaluepairs数组的单独字符串数组中的字符串。这样两个索引在单独的数组中相互匹配。
例如,在我将其拆分为int []数组和string []数组后,
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"
答案 0 :(得分:6)
int[] keys = partitioned.Select(pairs => pairs.Select(pair => pair.Key).ToArray())
.ToArray();
string[] values = partitioned.Select(pairs => pairs.Select(pair => pair.Value).ToArray())
.ToArray();
答案 1 :(得分: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();
答案 2 :(得分: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;
}
答案 3 :(得分: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);