这是我的建议:
- 对要排序的项目使用一个类,我建议使用
Tuple<T1, T2>
.
- 使用 a
List<T>
因为它是一个类型化的列表,因此可以避免强制转换,而且通常更方便。
- 我们将使用 Linq 对数组进行排序,以便于编写。
我列出下面的代码:
//I dunno what does this has to do, but I'll leave it here
ListBox.SelectedObjectCollection SelectedItems = lstSelectedFiles.SelectedItems;
//We are going to use a List<T> instead of ArrayList
//also we are going to use Tuple<DateTime, String> for the items
var LapsList = new List<Tuple<DateTime, String>>();
foreach (string Selected in SelectedItems)
{
XmlDocument xDoc = new XmlDocument();
xDoc.Load(Path + @"\" + Selected);
XmlNodeList Laps = xDoc.GetElementsByTagName("Lap");
foreach (XmlElement Lap in Laps)
{
var dateTime = DateTime.Parse(Lap.Attributes[0].Value);
var str = Lap.InnerXml.ToString();
//Here we create the tuple and add it
LapsList.Add(new Tuple<DateTime, String>(dateTime, str));
}
}
//We are sorting with Linq
LapsList = LapsList.OrderBy(lap => lap.Item1).ToList();
如果您不能使用元组,请为该项目声明您自己的类。例如
class Lap
{
private DateTime _dateTime;
private String _string;
public Lap (DateTime dateTimeValue, String stringValue)
{
_dateTime = dateTimeValue;
_string = stringValue;
}
public DateTime DateTimeValue
{
get
{
return _dateTime;
}
set
{
_dateTime = value;
}
}
public String StringValue
{
get
{
return _string;
}
set
{
_string = value;
}
}
}
使用此类,您可以轻松迁移代码,如下所示:
//I dunno what does this has to do, but I'll leave it here
ListBox.SelectedObjectCollection SelectedItems = lstSelectedFiles.SelectedItems;
//We are going to use a List<T> instead of ArrayList
//also we are going to use the Laps class for the items
var LapsList = new List<Lap>();
foreach (string Selected in SelectedItems)
{
XmlDocument xDoc = new XmlDocument();
xDoc.Load(Path + @"\" + Selected);
XmlNodeList Laps = xDoc.GetElementsByTagName("Lap");
foreach (XmlElement Lap in Laps)
{
var dateTime = DateTime.Parse(Lap.Attributes[0].Value);
var str = Lap.InnerXml.ToString();
//Here we create the Lap object and add it
LapsList.Add(new Lap(dateTime, str));
}
}
//We are sorting with Linq
LapsList = LapsList.OrderBy(lap => lap.DateTimeValue).ToList();
如果您不能使用 Linq,这里有一个非 Linq 替代方案:
LapsList.Sort
(
delegate(Tuple<DateTime, String> p1, Tuple<DateTime, String> p2)
{
return p1.Item1.CompareTo(p2.Item1);
}
);
或者对于使用 Lap 类的情况:
LapsList.Sort
(
delegate(Lap p1, Lap p2)
{
return p1.DateTimeValue.CompareTo(p2.DateTimeValue);
}
);