将Jagged数组转换为IEnumerable >?(Convert Jagged Array to IEnumerable>?)
我有这个Jagged数组:
( n在编译时给出,所以请假设所有值都已存在)
int[][] jagged = new int[n][]; jagged[0] = new int[3]; jagged[0][0] = 2; // Please ignore the dummy values.... jagged[0][1] = 55; jagged[0][2] = 4; jagged[1] = new int[3]; jagged[1][0] = 6; jagged[1][1] = 3; jagged[1][2] = 7; ... ... jagged[n] = new int[3]; jagged[n][0] = 9; jagged[n][1] = 5; jagged[n][2] = 1;我想从这个结构创建一个IEnumerable<KeyValuePair<int,int>> ,其中:
关键是: dummy value , 值为 n (虚拟值是唯一的)
(除了信息 - 我需要将图片映射到用户)
所以对于第一组我想:
{2-> 0} {55-> 0} {4-> 0}对于组#2
{6 -> 1} {3-> 1} {7-> 1} ... ... etc但作为一个整体清单:
因此,最终结果应为1 IEnumerable KeyValuePair<int,int> :
{2-> 0} {55-> 0} {4-> 0} {6 -> 1} {3-> 1} {7-> 1} ... {9 -> n} {5-> n} {1-> n}题 :
是否有任何Linq'y方式吗?(而不是循环遍历循环)?I have this Jagged Array :
(n is given at compile time , so please assume that all values are already there)
int[][] jagged = new int[n][]; jagged[0] = new int[3]; jagged[0][0] = 2; // Please ignore the dummy values.... jagged[0][1] = 55; jagged[0][2] = 4; jagged[1] = new int[3]; jagged[1][0] = 6; jagged[1][1] = 3; jagged[1][2] = 7; ... ... jagged[n] = new int[3]; jagged[n][0] = 9; jagged[n][1] = 5; jagged[n][2] = 1;I want to create a IEnumerable<KeyValuePair<int,int>> from this structure where :
key is : dummy value and the value is the n ( dummy value is unique)
(aside info - I need to map pictures to users)
So for group #1 I want:
{2-> 0} {55-> 0} {4-> 0}for group #2
{6 -> 1} {3-> 1} {7-> 1} ... ... etcBut as a whole list :
So final result should be 1 IEnumerable of KeyValuePair<int,int>:
{2-> 0} {55-> 0} {4-> 0} {6 -> 1} {3-> 1} {7-> 1} ... {9 -> n} {5-> n} {1-> n}Question :
Is there any Linq'y way of doing it ?(instead of loops over loops ) ?最满意答案
foreach (var t in jagged.SelectMany((row, rowIndex) => row.Select(value => new KeyValuePair<int, int>(value, rowIndex)))) { Console.WriteLine("{0} - {1}", t.Key, t.Value); } foreach (var t in jagged.SelectMany((row, rowIndex) => row.Select(value => new KeyValuePair<int, int>(value, rowIndex)))) { Console.WriteLine("{0} - {1}", t.Key, t.Value); }更多推荐
发布评论