简体   繁体   English

如何将多维数组转换为字典?

[英]How to convert a multi-dimensional array to a dictionary?

I have a n-by-3 array I wish to convert to a Dictionary<string,string[]> where the first column is the key and the rest of the column as an array for the value. 我有一个n-by-3数组,我想转换为Dictionary<string,string[]> ,其中第一列是键,列的其余部分作为值的数组。

For example: 例如:

Key = arr[0,0], Value = new string[2] {arr[0,1], arr[0,2]}.

I'm aware of ToDictionary but I don't know how to set the value part. 我知道ToDictionary但我不知道如何设置值部分。

arr.ToDictionary(x=>arr[x,0],x=>new string[2]{arr[x,1],arr[x,2]});
//This doesn't work!!!

How can I set it up correctly? 如何正确设置?

Multidimensional arrays are a continuous block of memory, so you kind of have to treat them like a single array. 多维数组是一个连续的内存块,因此您必须将它们视为单个数组。 Try this: 尝试这个:

var dict = arr.Cast<string>() 
  .Select((s, i) => new { s, i })
  .GroupBy(s => s.i / arr.GetLength(1))
  .ToDictionary(
    g => g.First().s,
    g => g.Skip(1).Select(i => i.s).ToArray()
  );

With explanations: 有解释:

// First, cast it to an IEnumerable<string>
var dict = arr.Cast<string>() 

  // Use the Select overload that lets us get the index of the element,
  // And we capture the element's index (i), along with the element itself (s)
  // and put them together into an anonymous type [1]
  .Select((s, i) => new { s, i })

  // .GetLength(dimension) is a method on multidimensional arrays to 
  // get the length of a given dimension (pretty self-explanatory)
  // In this case, we want the second dimension, or how wide each 
  // row is: [x,y] <- we want y
  // Divide the element index (s.i) by that length to get the row index 
  // for that element
  .GroupBy(s => s.i / arr.GetLength(1))

  // Now we have an Grouping<int, IEnumerable<anonymous{string,int}>>
  .ToDictionary(

    // We don't care about the key, since it's the row index, what we want
    // is the string value (the `s` property) from first element in the row
    g => g.First().s,

    // For the value, we want to skip the first element, and extract
    // the string values (the `s` property), and then convert to an array
    g => g.Skip(1).Select(i => i.s).ToArray()
  );

[1]: See here for documentation on anonymous types. [1]:有关匿名类型的文档,请参见此处

This is the simplest approach I can come up with: 这是我能想出的最简单的方法:

var arr = new int[4, 3]
{
    { 1, 2, 3 },
    { 3, 5, 7 },
    { 5, 8, 11 },
    { 7, 11, 15 },
};

var dict = arr.Cast<int>().Buffer(3).ToDictionary(x => x[0], x => x.Skip(1).ToArray());

That gives me: 这给了我:

字典

You just need to NuGet "System.Interactive" to get the Buffer operator. 您只需要NuGet“System.Interactive”来获取Buffer运算符。

Or use this implementation: 或者使用此实现:

public static IEnumerable<T[]> Buffer<T>(this IEnumerable<T> source, int count)
    =>
        source
            .Select((t, i) => new { t, i })
            .GroupBy(x => x.i / count)
            .Select(x => x.Select(y => y.t).ToArray());

I guess your approach was right ,my only doubt is that your array is static or not? 我想你的方法是正确的,我唯一的疑问是你的阵列是静态的还是不是?

arr.Select((value, index) => new { value, index }) .ToDictionary(x => x.index, x => new string[2]{x.value[x.index][1],x.value[x.index][2]}));

Note: I couldn't execute and check the code ! 注意:我无法执行并检查代码! Sorry. 抱歉。

Sometimes not using linq is easier to read and faster: 有时不使用linq更容易阅读和更快:

 var dict = new Dictionary<string, string[]>();
 for (int i = 0; i < arr.GetLength(0); i++)
      dict[arr[i, 0]] = new string[] { arr[i, 1], arr[i, 2] };

But when you feel like you REALLY need to use linq: 但是当你觉得你真的需要使用linq时:

 Enumerable.Range(0, arr.GetLength(0))
     .ToDictionary(i => arr[i, 0], i => new string[] {arr[i, 1], arr[i, 2]});

I had done using Integer. 我用过Integer。 Please Change for your requirements. 请根据您的要求进行更改。

public static void Main()
{ 
    int row=0 , col=0;
    int[,] array = new int[,]
    {
     { 1, 2, 3 },
     { 4, 5, 6 }, 
     { 7, 8, 9 },
     { 10, 11, 12 } 
    };

    int flag=0;

    for (int i = 0; i < array.Rank; i++)
    {
                if(flag==0)
                {
        row= array.GetLength(i);
                    flag=1;
                }
                else
                {

         col= array.GetLength(i);       
                }

        }

    Dictionary<int,int[,]> dictionary = new Dictionary<int, int[,]>();

    for(int i=0;i<row;i++)
    {

        dictionary.Add(array[i,0],new int[, ]{{array[i,1]},{array[i,2]}});

    }

    Console.WriteLine(dictionary[4].GetValue(0,0));

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM