PDA

View Full Version : [C#] Ordinare una ArrayList....


race2
04-04-2008, 15:00
Salve,
in una ArrayList ho insrtito delle Istanze di una mia Classe,
vorrei potere ordinale l'ArrayList per l'item id (int) che risiede nella mia Istanza....


class Row
{
private int m_id;
private string m_label;

public Row(int id, string label)
{
m_id = id;
m_label = label;
}

public int id()
{
return m_id;
}

public string label()
{
return m_label;
}
}


ArrayList aRowsExcel = new ArrayList();

for (int i=0; i<=10; i++)
{
aRowsExcel.Add(new Row(i, "bla-bla");
}

aRowsExcel.sort();//non mi controlla il campo che volgio ordinare


come posso fare per ordinare per id ???

kernel::panic
04-04-2008, 15:13
Se usi il FW 2.0 o superiore puoi usare la List<Row> che ha un metodo Sort al quale puoi passare una callback in cui fai i dovuti confronti.

Oppure implementi IComparable:
class Row:IComparable
{
public int CompareTo(object obj)
{
if(obj is Row)
return this.m_id.CompareTo((obj as Row).m_id);
else
return -1;
}
}

Ciao ;)

0rph3n
04-04-2008, 15:39
scritto su due piedi:

ArrayList<Row> excelRows = new ArrayList<Row>();

for (int i=0; i<=10; i++)
{
excelRows.Add(new Row(i, "bla-bla");
}

ArrayList<Row> orderedLinkedList = (from excelRow in excelRows
orderby excelRow.id
select excelRow).ToList();

questo ovviamente se usi la versione del framework che supporta generics e linq (versione che in questo preciso moment mi sfugge :D )

race2
04-04-2008, 16:13
Funziona, fantastico, grazie mille kernel::panic ...!!!!

A presto, ciao!

race2
04-04-2008, 16:24
scritto su due piedi:

ArrayList<Row> excelRows = new ArrayList<Row>();

for (int i=0; i<=10; i++)
{
excelRows.Add(new Row(i, "bla-bla");
}

ArrayList<Row> orderedLinkedList = (from excelRow in excelRows
orderby excelRow.id
select excelRow).ToList();

questo ovviamente se usi la versione del framework che supporta generics e linq (versione che in questo preciso moment mi sfugge :D )


non importa, ho la 3.5 quindi non ci sono problemi, perfetto, grazie mille !!!!