SamW
SamW

Reputation: 3

Sort a List of Arrays

I have a series of string fields for an object. I want to create multiple in a loop, and then sort them based on one of the fields. Here is what i have so far

string[] EventArray = new string[3];
    EventArray[0] = "STRStartDateTime" //Sort by this field A->Z
    EventArray[1] = "StartTimeOut";
    EventArray[2] = "EndTimeOut";
List<Array> EventsUnsorted = new List<Array>();
EventsUnsorted.Add(EventArray);

//Sort Events

foreach (Array Event in EventsSorted)
{
    string Output = Event.GetValue(2).ToString();
}

What method should I use for sorting and generally have I taken the right approach for storing data like this?

Upvotes: 0

Views: 932

Answers (4)

Jeremy Smith
Jeremy Smith

Reputation: 1469

The two easiest options are:

  • EventsUnsorted.Sort() - By default, a List<String> uses a current culture, case-insensitive ascending sort.

  • EventsUnsorted.OrderBy() - You'll supply the field(s) to sort by e.g. .OrderBy(x=>x.EventID)

Upvotes: 1

Felipe Oriani
Felipe Oriani

Reputation: 38638

Try using a List<string[]> and add the itens ordered, for sample:

// create the array
string[] EventArray = new string[3];
EventArray[0] = "STRStartDateTime"
EventArray[1] = "StartTimeOut";
EventArray[2] = "EndTimeOut";

// create the list
List<string[]> EventsUnsorted = new List<string[]>();
EventsUnsorted.Add(EventArray);

// sort by 0 index
EventsUnsorted = EventsUnsorted.OrderBy(x => x[0]).ToList(); 

foreach (string[] e in EventsSorted)
{
    string Output = e[2].ToString();
}

Upvotes: 0

Seb
Seb

Reputation: 1230

Use this simple Linq expression :

var EventsSorted = EventsUnsorted.OrderBy(event => event[0]);

Upvotes: 1

Raju Padhara
Raju Padhara

Reputation: 707

Use Array.Sort method.

string[] EventArray = new string[3];
    EventArray[0] = "STRStartDateTime" //Sort by this field A->Z
    EventArray[1] = "StartTimeOut";
    EventArray[2] = "EndTimeOut";
Array.Sort(EventArray); 

Upvotes: -1

Related Questions