scottdf93
scottdf93

Reputation: 40

How to sort a list of Classes

I have a class called DataStore and in that i have the following;

string Name;
DateTime Date;
double Code;

In the main form i have the list below;

List<DataStore> ListOfDataStore = new List<DataStore>

I create instances of this class in the main form and assign values from what the user inputs and store them in the list below;

 DataStore dataStore = new DataStore();
 dataStore.Name = "abc";
 dataStore.Date = new DateTime(Year,Month,Day);
 dataStore.Code = 10;
 ListOfDataStore.Add(dataStore);

 DataStore dataStore = new DataStore();
 dataStore.Name = "def";
 dataStore.Date = new DateTime(Year,Month,Day);
 dataStore.Code = 20;
 ListOfDataStore.Add(dataStore);

 DataStore dataStore = new DataStore();
 dataStore.Name = "ghi";
 dataStore.Date = new DateTime(Year,Month,Day);
 dataStore.Code = 30;
 ListOfDataStore.Add(dataStore);

I now want to sort ListOfDataStore by what is in each of the dataStore.Namebut I cant work out how to access the string Name without giving an index of the list ListOfDataStore.

Any guidance is much appreciated.

Upvotes: 1

Views: 66

Answers (2)

Mel Gerats
Mel Gerats

Reputation: 2252

If you want to sort the list in place:

ListOfDataStore.Sort((x, y) => x.Name.CompareTo(y.Name));

If you want a new collection ordered by name:

var orderedListOfDataStore = ListOfDataStore.OrderBy(item => item.Name);

Upvotes: 3

Antoine V
Antoine V

Reputation: 7204

LinQ can help you to order a list with the method OrderBy or OrderByDescending

var sorted = ListOfDataStore.OrderBy(d=> d.Name)

Upvotes: 2

Related Questions