C#:将1D阵列拆分为2D阵列

时间:2017-04-23 20:15:58

标签: c# arrays multidimensional-array

我有一维数组:

string[] Technology = new [] {Smartphone, Laptop, Tablet, Desktop, Server, Mainframe};

如何将这个分成两半并将两个部分放入一个更大的2D数组中,以便以下两个部分都返回true

// categorizedTechnology[0].SequenceEquals(new [] {Smartphone, Laptop, Tablet});
// categorizedTechnology[1].SequenceEquals(new [] {Desktop, Server, Mainframe});

2 个答案:

答案 0 :(得分:0)

如果您有6个项目,则可以执行此操作:

string[] Technology = new string[6] { "Smartphone", "Laptop", "Tablet", "Desktop", "Server", "Mainframe" };

var firstChunk = Technology.Take(3);
var secondChunk = Technology.Skip(3).Take(3);

string[,] array2D = new string[,] { 
   { firstChunk.First(), firstChunk.Skip(1).First(), firstChunk.Last()},
   { secondChunk.First(), secondChunk.Skip(1).First(), secondChunk.Last()} };

或者只是这样做:

string[,] array2D = new string[,] { 
        { Technology[0], Technology[1], Technology[2]},
        { Technology[3], Technology[4], Technology[5]} };

答案 1 :(得分:0)

如果你想明确指定哪个项目进入哪个bin,那么你需要创建另一个包含该类别的数组。我选择使用一系列的bool'指示每件物品是否可携带。然后我将两个阵列压缩在一起并将它们过滤为便携式或非便携式。

string[] technology = new string[] { "Smartphone", "Laptop", "Tablet", "Desktop", "Server", "Mainframe" };
bool[] isPortable = new bool[] { true, true, true, false, false, false };
string[][] categorizedTechnology = new string[][] 
{
    technology.Zip(isPortable, (tech, test)=> test?tech: null).Where( tech=> tech!=null ).ToArray(),
    technology.Zip(isPortable, (tech, test)=> test?null: tech).Where( tech=> tech!=null ).ToArray()
};

但这仍然不是正确的做法。面向对象编程很重要,因为技术是类别信息需要组合成单个实体,如类或结构。

这就是使用类和LINQ

的样子
public class Technology
{
    public string Name { get; set; }
    public bool IsPortable { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        Technology[] list = new Technology[] {
            new Technology() { Name="Smartphone", IsPortable=true },
            new Technology() { Name="Laptop", IsPortable=true },
            new Technology() { Name="Tablet", IsPortable=true },
            new Technology() { Name="Desktop",  IsPortable=false },
            new Technology() { Name="Server",   IsPortable=false },
            new Technology() { Name="Mainframe", IsPortable=false },
        };

        Technology[][] groupedTechnology 
            = list.GroupBy((tech) => tech.IsPortable)
                .Select((group) => group.ToArray()).ToArray();
    }
}