gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 20:02:22 24 4
gpt4 key购买 nike

给定位置的列表,我需要执行 2 个排序步骤。

  1. LocationType 升序排列。
  2. 对于每个位置类型值,按 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 ...

这是主要代码(从那个 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);
}
}

最佳答案

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;

关于c# - 如何按两个属性对这个简单的 .NET 列表进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26607443/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com