Given a list/array of objects containing some other objects, I'm looking to sort by using one of the parameters. For example, if I have a multi-dimensional array of ints and I want to sort by their midpoint.
The way I'm doing it is to create an anonymous object containing 1. the midpoint and 2. a list of the 2 ints for each entry. Then enlist these objects and use reflection to access and sort by the midpoint parameter.
Is there a more standard approach to this problem? It's a bit clumsy because I have to create a dummy and clear the anonymous list object in order to do it.
class Program
{
static void Main(string[] args)
{
int[,] input = new int[,] { { 5, 6 }, { 0, 1 }, { 2, 20 } };
var itemList = new []{
new { sortVar = 0.1f, item = new List<int>() } }.ToList();
itemList.Clear();
for(int i=0; i<input.GetLength(0); i++)
{
List <int> temp = new List<int> (new int[] { input[i,0], input[i, 1] });
var item = new {
sortVar = float.Parse((input[i,0]+input[i,1]).ToString())/2,
item = temp };
itemList.Add(item);
}
var itemList2 = itemList.OrderBy(x => x.sortVar);
}
}