PROWAREtech
.NET: Sort a List of Objects with a Delegate Function
How to use a delegate to sort a C# List Holding Objects Instead of Primitive Types.
Use a delegate for basic sorting of objects in a List
.
// NOTE: Declare the class to create objects with
public class User
{
public string Name { get; set; }
public int Age { get; set; }
public User(string name, int age)
{
Name = name;
Age = age;
}
}
// NOTE: Create the data to sort
List list = new List();
list.Add(new User("Jack", 40));
list.Add(new User("John", 33));
list.Add(new User("Jimmy", 35));
list.Add(new User("Jacquelin", 40));
list.Add(new User("George", 40));
list.Add(new User("Denny", 28));
// NOTE: Sort ascending
list.Sort(delegate(User x, User y)
{
return x.Age.CompareTo(y.Age);
});
// NOTE: Sort descending
list.Sort(delegate(User x, User y)
{
return y.Age.CompareTo(x.Age);
});
// NOTE: Sort by more than on property
list.Sort(delegate(User x, User y)
{
// NOTE: Sort by age in ascending order
int z = x.Age.CompareTo(y.Age);
// NOTE: When both users have the same age, sort by name in ascending order
if (z == 0)
z = x.Name.CompareTo(y.Name);
return z;
});
Here is an example of sorting a List
by the image ratio putting the squarest ones first. This can be useful for finding images for the purposed of machine learning.
// NOTE: A class can also be used in the same manner
record ImageDimension(string path, int width, int height);
// NOTE: Create the data
List imagesDims = new List();
imagesDims.Add(new ImageDimension("image1.jpg", 100, 50));
imagesDims.Add(new ImageDimension("image2.jpg", 100, 100));
imagesDims.Add(new ImageDimension("image3.jpg", 50, 50));
imagesDims.Add(new ImageDimension("image4.jpg", 90, 60));
imagesDims.Add(new ImageDimension("image5.jpg", 720, 1280));
imagesDims.Add(new ImageDimension("image6.jpg", 1024, 768));
// NOTE: Sort putting the squarest images first; the more rectangular ones will be placed in the end
imagesDims.Sort(delegate (ImageDimension x, ImageDimension y)
{
double xRatio = Math.Min(x.width, x.height) / (double)Math.Max(x.width, x.height);
double yRatio = Math.Min(y.width, y.height) / (double)Math.Max(y.width, y.height);
return yRatio.CompareTo(xRatio);
});
Comment