1) How to order/sort a list of custom objects by property
class Person
{
public string
FirstName;
public string
LastName;
public DateTime DOB;
}
List<Person>
people = new List<Person>()
{
new Person() {FirstName = "Bob", LastName = "Funnyman", DOB = new
DateTime(1980, 1, 1) },
new Person() {FirstName = "Tom", LastName = "Sadman", DOB = new
DateTime(1970, 1, 1) },
new Person() {FirstName = "Abe", LastName = "Justman", DOB = new
DateTime(1990, 1, 1) },
new Person() {FirstName = "Abe", LastName = "Justman", DOB = new
DateTime(1984, 1, 1) },
};
List<Person>
sortedPeorsonList = people.OrderBy(o => o.DOB).ThenBy(o =>
o.LastName).ThenBy(o => o.FirstName).ToList();
2a) Create a sorted list of Keys form a Dictionary depending on
the values
Dictionary<string, int> stringsDictionary = new Dictionary<string, int>()
{
["one"] = 1,
["ten"] = 10,
["two"] = 2,
["four"] = 4,
["three"] = 3,
};
List<string>
result = (from entry in stringsDictionary orderby entry.Value ascending select entry.Key).ToList();
2b) If you wish sort and to keep the key-pair values
List<KeyValuePair<string, int>> sortedKeyValuePairs = stringsDictionary.OrderBy(d => d.Value).ToList();
Comments
Post a Comment