C#对锯齿状的对象数组进行排序 [英] C# Sorting a jagged array of objects
本文介绍了C#对锯齿状的对象数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用C#,我有一个包含对象的2D锯齿形数组,我想要实现的是基于这些对象内的公共属性对这个锯齿形数组进行排序我在下面创建了我的问题的样本,我使用LINQ的经验有限,但是我尝试使用它并失败了,如果需要的话,我还着手创建交换方法.
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();
}
推荐答案
下面的代码按一维排序
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);
}
}
}
这篇关于C#对锯齿状的对象数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文