将两个不同类型的列表连接在一起
本文关键字:同类型 列表 连接 在一起 两个 | 更新日期: 2023-09-27 18:02:33
我正在尝试制作一个程序,让用户输入一些城市和城市的温度。稍后,温度列表会自动排序,这样我就可以得到列表中最冷和最热的城市。但问题是只有具有温度的列表才会被排序。这使得城市的温度与以前不同。
那么我能否将两个列表链接在一起,这样当第二个列表中的温度发生变化时,最初获得该温度的城市的位置就会发生变化?
我对编程有点陌生。
谢谢。
您可能希望将城市名称和城市温度放在一起,如
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
你需要有结构来把城市和温度结合在一起。例如
public class CityInfo
{
public string CityName {get; set;}
public float Temperature {get; set;}
}
然后创建该类的列表。
List<CityInfo> citiInfos = new List<CityInfo>();
那么你可以基于:
on city name:
var sortedByCity = citiInfos.OrderBy(cityInfo => cityInfo.CityName);
在温度:
var sortedByTemp = citiInfos.OrderBy(cityInfo => cityInfo.Temperature);
建议创建一个包含城市信息和相应温度的对象,例如
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));
...
那么你可以用cityListName.OrderBy((city)=>city.Temperature)
List
按温度排序我希望这有帮助。