我有 2 个列表,什么是对:
List<int> timeStamp = new List<int>();
List<string> ownerStamp = new List<string>();
例如:timeStamp' 元素:1、10、32 ...
ownerStamp' 元素:John、Dave、Maria ...
对是:John-1;戴夫-10;玛丽亚-32...
我必须订购时间戳列表的元素,但我必须保留上下文!我该怎么做?手动?还是通过工厂订购来聪明?
我有 2 个列表,什么是对:
List<int> timeStamp = new List<int>();
List<string> ownerStamp = new List<string>();
例如:timeStamp' 元素:1、10、32 ...
ownerStamp' 元素:John、Dave、Maria ...
对是:John-1;戴夫-10;玛丽亚-32...
我必须订购时间戳列表的元素,但我必须保留上下文!我该怎么做?手动?还是通过工厂订购来聪明?
Array.Sort() 方法有一个重载,它允许您使用其他数组项作为键对一个数组进行排序。您可以将列表转换为数组,然后对它们进行排序,然后再转换回来:
List<int> timeStamp = new List<int>();
List<string> ownerStamp = new List<string>();
int[] timeStampArray = timeStamp.ToArray();
string[] ownerStampArray = ownerStamp.ToArray();
Array.Sort(timeStampArray, ownerStampArray);
timeStamp = new List<int>(timeStampArray);
ownerStamp = new List<string>(ownerStampArray);
您最好制作一个包含所有者和时间戳的容器对象,并使其具有可比性:
class Entry : IComparable<Entry> {
public int TimeStamp { get; set; }
public string Owner { get; set; }
public Entry(int timeStamp, string owner) {
this.TimeStamp = timeStamp;
this.Owner = owner;
}
public int CompareTo(Entry other) {
return this.TimeStamp.CompareTo(other.TimeStamp);
}
}
然后,您可以列出这些列表并使用List<T>
Sort()
方法对其进行排序。
要访问时间戳和所有者,TimeStamp
只需Owner
访问Entry
.
通常,如果您希望数据属于一起,最好将它们明确地组合在一个对象或结构中;然后分组将自动发生,您无需特别注意将事物分组。
您的问题没有具体说明您期望的输出,但以下将为您提供 Tuple 对象的排序集合,其第一项是时间戳,第二项是所有者。
timeStamp.Zip(ownerStamp, (i,s) => Tuple.Create(i,s)).OrderBy(t => t.Item1)
最好将这些对组合成一个“SortedDictionary”,它会自动为你对这些对进行排序,或者为timeStamp
and创建一个元组列表ownerStamp
,然后根据timeStamp
键对元组列表中的元素进行排序。
排序的字典可能会有所帮助。