-3

我正在尝试制作一个程序,让用户输入一些城市和城市的温度。稍后,带有温度的列表将自行排序,以便我可以得到列表中最冷和最热的城市。但问题是只有带有温度的列表才会被排序。这使得城市的温度与以前不同。

那么我可以将两个列表链接在一起,以便当第二个列表中的温度发生变化时,最初获得温度的城市会改变位置吗?

我对编程有点陌生。

谢谢。

4

3 回答 3

5

你可能想把城市名称和城市温度放在一起,比如

public class City
{
    public string Name;
    public double Temperature;
    // etc.
}

然后创建一个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();

编辑:

如果您使用的是 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);
        }
    }
    

    然后你可以用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
    
于 2013-03-05T12:10:42.483 回答
2

您需要具有将城市和温度结合在一起的结构..例如

public class CityInfo 
{ 
  public string CityName {get; set;}
  public float Temperature {get; set;}
}

然后创建这个类的列表。

List<CityInfo> citiInfos = new List<CityInfo>();

然后你可以根据排序:

关于城市名称:

var sortedByCity = citiInfos.OrderBy(cityInfo => cityInfo.CityName);

关于温度:

var sortedByTemp = citiInfos.OrderBy(cityInfo => cityInfo.Temperature);
于 2013-03-05T12:12:22.933 回答
1

我建议您创建一个包含城市信息和相应温度的对象,例如

class City
{
    public string Name {get; private set;}
    public int Inhabitants {get; private set;}
    public float Temperature {get; private set;}

    public City (string name, int inhabitants, float temp)
    {
        Name = name;
        Inhabitants = inhabitants;
        Temperature = temperature;
    }
}

然后创建一个List<City>,添加你的城市

cityListName.Add(new City("CityName",9000,16.5));
...

然后你可以List按温度排序cityListName.OrderBy((city)=>city.Temperature)

我希望这会有所帮助。如果您还有其他问题,请随时提问。

于 2013-03-05T12:10:49.600 回答