在C#中是否可以创建多维数组列表?
StartDate Qty size
9/1/2010 10 15
9/1/2009 12 17
9/1/2008 11 19
StartDate
,Qty
和size
是三个ArrayList。我需要将它们合并为一个ArrayList,并且需要按照StartDate
进行排序。这是否可能?是否有比使用ArrayList更好的方法?
public class Info
{
public DateTime StartDate { get; set; }
public int Qty { get; set; }
public int Size { get; set; }
}
然后只需拥有一个普通的List来容纳这些对象:
List<Info> infoList = new List<Info>();
这将使你不必担心每个列表的排序。要处理排序,你可以使用LINQ to Objects扩展方法:
var sortedList = infoList.OrderBy(i => i.StartDate);
如果可以的话,建议采用Justin的答案。因为每个属性都有意义,这样可以在长期运行中避免出现问题。如果需要快速处理且你使用的是.NET 4,则可以将Tuple
列在列表中。
List<Tuple<DateTime, int, int>> myData = new List<Tuple<DateTime, int, int>>();
myData.Add(new Tuple<DateTime, int, int>(DateTime.Now, 1, 2));
//
DateTime myDate = myData[0].Item1;
int myQty = myData[0].Item2;
int mySize = myData[0].Item3;
// descending sort done in place using List<>.Sort
myData.Sort((t1, t2) => -1 * t1.Item1.CompareTo(t2.Item1));
// descending sort performed as necessary in a sequence
var orderedList = myData.OrderByDescending(t => t.Item1);
var
,通常只在处理查询时使用它(有时甚至连那都不用)。对于其他所有情况,我更喜欢始终保持明确。 - Anthony Pegram你想要一个列表的列表。也没有理由使用ArrayList。从你的例子中:
List<List<DateTime>> list = new List<List<DateTime>>();
话虽如此,我更喜欢像Justin上面展示的那样。
public class MyClass
{
public DateTime StartDate {get;set;}
public int Qty {get;set;}
public int Size {get;set;}
}
List<MyClass> myClassArray = new List<MyClass>();
public struct MyStruct
{
public DateTime StartDate { get; set; }
public int Qty { get; set; }
public int Size { get; set; }
}
...
List<MyStruct> MyList = new List<MyStruct>();
...
MyList.Sort((item1, item2) => item1.Qty.CompareTo(item2.Qty)); //ascending sort
...
MyList.Sort((item1, item2) => item2.Qty.CompareTo(item1.Qty)); //descending sort
SortedList<>
,并将一个包含 3 个 List<>
实例的对象添加到其中。然后,你需要编写一个比较器来按 StartDate
对你的对象进行排序。
OrderByDescending()
。 - Jeff Mercado