C# Sorting a jagged array of objects

旧巷老猫 提交于 2021-02-08 09:56:52

问题


Using C#, I have a 2D Jagged array containing objects, what I want to achieve is to sort this Jagged array based on a public property within these objects I have created a sample below of my problem, I have limited experience with using LINQ, but I have attemped using it and have failed, I have also proceeded to create a swap method if needed.

Any insight would be much welcomed, thank you

    //[][] of Objects
    private MyObject[][] jaggedArray = new MyObject[3][]
    {
        new MyObject[5]
        {
            new MyObject(), new MyObject(), new MyObject(), new MyObject(), new MyObject(),
        },
        new MyObject[5]
        {
            new MyObject(), new MyObject(), new MyObject(), new MyObject(), new MyObject(),
        },

        new MyObject[5]
        {
            new MyObject(), new MyObject(), new MyObject(), new MyObject(), new MyObject(),
        },
    };


    static void swap(ref MyObject a, ref MyObject b)
    {
        MyObject temp = a;
        a = b;
        b = temp;
    }

class MyObject
{
    public MyObject()
    { Value = rand.Next(100);    }
    public int Value{ get; set; }

    Random rand = new Random();
}

回答1:


Code below sorts in one dimension

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            new Test();
        }
    }
    public class Test
    {
        //[][] of Objects
        private MyObject[][] jaggedArray = new MyObject[3][]
        {
            new MyObject[5]
            {
                new MyObject(), new MyObject(), new MyObject(), new MyObject(), new MyObject(),
            },
            new MyObject[5]
            {
                new MyObject(), new MyObject(), new MyObject(), new MyObject(), new MyObject(),
            },

            new MyObject[5]
            {
                new MyObject(), new MyObject(), new MyObject(), new MyObject(), new MyObject(),
            },
        };

        public Test()
        {
            jaggedArray = jaggedArray.Select(x => x.OrderBy(y => y).ToArray()).ToArray();
        }
    }
    public class MyObject : IComparable<MyObject>
    {
        public MyObject()
        { 
            Value = rand.Next(100);    
        }
        public int Value{ get; set; }

        static Random rand = new Random();

        public int CompareTo(MyObject o)
        {

            return this.Value.CompareTo(o.Value);
        }
    }
}


来源:https://stackoverflow.com/questions/43306520/c-sharp-sorting-a-jagged-array-of-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!