如何按两个属性对这个简单的.NET列表进行排序

本文关键字:列表 NET 排序 简单 何按两 属性 | 更新日期: 2023-09-27 18:28:02

给定一个Location的列表,我需要执行两个排序步骤。

  1. LocationType升序排序
  2. 对于每个位置类型的值,按Name升序排列这些结果

样本数据:

Location Type | Name
            2 | Templestowe Lower
            2 | Templestowe
            1 | Melbourne

预期结果:

1. Melbourne
2. Templestowe
3. Templestowe Lower

这是一个(不起作用).NET Fiddle。。。

这是主代码(从小提琴上复制的)。。

private class Location
{
    public Location (string name, int locationType)
    {
        Name = name;
        LocationType = locationType;
    }
    public string Name { get; private set; }
    public int LocationType { get; private set;}
}
public static void Main()
{
    var locations = new List<Location> 
    {
        new Location("Templestowe Lower", 2),
        new Location("Templestowe", 2),
        new Location("Melbourne", 1)
    };
    // TODO: return a list, sorted by LocationType and name.
    var results = XXXXX;
    foreach(var location in results)
    {
        Console.WriteLine(location.Name);
    }
}

如何按两个属性对这个简单的.NET列表进行排序

locations.Sort((x,y) => {
   int delta = x.LocationType.CompareTo(y.LocationType);
   if(delta == 0) delta = string.Compare(x.Name, y.Name);
   return delta;
});

或者:

var results = locations.OrderBy(x => x.LocationType).ThenBy(x => x.Name);

或者在LINQ语法中(编译为相同的东西):

var results = from loc in locations
              orderby loc.LocationType, loc.Name
              select loc;

通过使用组检查

var results = locations
            .GroupBy(x => x.LocationType)
            .OrderBy(x => x.Key)
            .SelectMany(g => g.OrderBy(x=>x.Name));