问题
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