给定Location
的列表,我需要做两个订购步骤。
LocationType
升序排序。 Name
升序。示例数据:
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);
}
}
答案 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));