I have a list of names, and I want to implement a custom ordering by implementing the IComparer<T>
interface. This custom sort must check the first names of two items, and if they are the same, it should group them together. For example, the final result should be:
John Locke
John Doe
Elizabeth Davis
Elizabeth Hurley
Ashley Williams
I do not want to change the ordering of the list by first name. I just want to group together items with the same first name, but different last names.
class Program
{
static void Main(string[] args)
{
List<Name> names = new List<Name>
{
new Name {FirstName = "John", LastName = "Locke"},
new Name {FirstName = "Elizabeth", LastName = "Davis"},
new Name {FirstName = "John", LastName = "Doe"},
new Name {FirstName = "Ashley", LastName = "Williams"},
new Name {FirstName = "Elizabeth", LastName = "Hurley"}
};
foreach (Name name in names)
{
Console.WriteLine($"{name.FirstName, -10} {name.LastName, -10}");
}
Console.WriteLine("\n\n");
List<Name> sorted = names.OrderBy(o => o, new NameComparer()).ToList();
foreach (Name name in sorted)
{
Console.WriteLine($"{name.FirstName,-10} {name.LastName,-10}");
}
Console.ReadKey();
}
}
public sealed class Name
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
public sealed class NameComparer : IComparer<Name>
{
public int Compare(Name x, Name y)
{
}
}