如何通过两个属性订购这个简单的.NET列表?

时间:2014-10-28 11:40:55

标签: c# .net linq sql-order-by partitioning

给定Location的列表,我需要做两个订购步骤。

  1. LocationType升序排序。
  2. 对于每个位置类型值顺序,这些结果由Name升序。
  3. 生成

    示例数据:

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

    预期结果:

    1. Melbourne
    2. Templestowe
    3. Templestowe Lower
    

    Here is a (not working) .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);
        }
    }
    

2 个答案:

答案 0 :(得分:6)

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;

答案 1 :(得分:-1)

使用分组

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