giovedì 8 marzo 2012

HowTo :linq Sort / Order with 2 fields

Dopo qualche tempo d'assestamento eccomi di nuovo a voi, per una breve ma carina soluzione.

si tratta di un semplice sort con linq, ed è noto che linq e semplice non sempre vanno di pari passo.

Devo essere onesto questa soluzione non mi convince del tutto.

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

namespace TestStort
{
public class entity
{
public int idC { get; set; }
public int idD { get; set; }

}
public class entities : List<entity>
{

}
class Program
{
static void Main(string[] args)
{
entities ex = new entities();
for (int j = 0; j < 5; j++)
{
Random r = new Random(j);

int r1 = r.Next(100);

int r2 = r.Next(1000);

ex.Add(new entity() { idC = r1, idD =r2 });

r = null;
}

var ex_s = ex;

var ex_o = ex.OrderBy(e => e.idD).OrderBy(e=> e.idC).ToList<entity>();

for (int i = 0; i < 5; i++)
{
Console.WriteLine("Orig:\t\t {0} \t{1}", ex_s[i].idC, ex_s[i].idD);
}

Console.WriteLine("----------------------------------------------------");

for (int i = 0; i < 5; i++)
{
Console.WriteLine("Sort:\t\t {0} \t{1}", ex_o[i].idC, ex_o[i].idD);
}

Console.ReadLine();
}
}
}

Nessun commento: