-3 c#
我正在尝试制作一个程序,让用户可以放入一些城市和城市的温度.之后,温度列表将自行排序,以便我可以获得列表中最冷和最热的城市.但问题是只有温度列表才会被排序.这使得城市的温度与以前不同.
那么我可以将两个列表链接在一起,这样当第二个列表中的温度发生变化时,原来得到温度的城市会改变到哪个位置?
我对编程很陌生.
谢谢.
你可能想把城市名称和城市温度放在一起,比如
public class City
{
public string Name;
public double Temperature;
// etc.
}
Run Code Online (Sandbox Code Playgroud)
然后创建一个List<City>并且只要您需要根据特定字段对该列表进行排序,就可以使用Linq(using System.Linq;)对列表进行排序
List<City> sortedList = cityList.OrderBy(city => city.Temperature).ToList();
// or if you want the list sorted the other way around:
sortedList = cityList.OrderByDescending(city => city.Temperature).ToList();
Run Code Online (Sandbox Code Playgroud)
编辑:
如果您使用的是3.5之前的.NET版本,则不会有任何Linq,因此您需要一些替代方案:
如果您只需要一个排序顺序,则可以实现该IComparable接口
public class City : IComparable
{
public int CompareTo(object obj)
{
City other = obj as City;
if (other == null)
// obj was not a City, so this should throw an exception in my opinion
throw new ArgumentException;
return this.Temperature.CompareTo(other.Temperature);
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以用列表对列表进行排序 cityList.Sort()
或者,如果您希望能够按温度(有时按名称)对列表进行排序,则需要与代表一起工作
cityList.Sort(delegate (City a, City b)
{
// -1 => a < b
// 0 => a == b
// 1 => a > b
return a.Name.CompareTo(b.Name);
});
// cityList is now sorted by name
cityList.Sort(delegate (City a, City b)
{
// -1 => a < b
// 0 => a == b
// 1 => a > b
return a.Temperature.CompareTo(b.Temperature);
});
// cityList is now sorted by temperature
Run Code Online (Sandbox Code Playgroud)