I want to create a multidimensional array that includes an integer element and a datetime element. I want to be able to sort on the datetime element and grab the integer elements according to the sorted datetime elements. Is there a way to do this with arrays in c#, or should I be using something more like a datatable?
-
multidimentional? how do you want to sort it?Grzenio– Grzenio2009-12-10 16:21:34 +00:00Commented Dec 10, 2009 at 16:21
-
I think Ben meant a array of 2 columns, DateTime and int, like Dictionary<DateTime, int>serhio– serhio2009-12-10 16:39:43 +00:00Commented Dec 10, 2009 at 16:39
Add a comment
|
4 Answers
for keep interegs and DateTimes, use the generic System.Collections.Dictionary<DateTime, int>
for keep the order, use System.Collections.Specialized.OrderedDictionary. See example in MSDN(here).
// Creates and initializes a OrderedDictionary.
OrderedDictionary myOrderedDictionary = new OrderedDictionary();
myOrderedDictionary.Add("testKey1", "testValue1");
myOrderedDictionary.Add("testKey2", "testValue2");
myOrderedDictionary.Add("keyToDelete", "valueToDelete");
myOrderedDictionary.Add("testKey3", "testValue3");
ICollection keyCollection = myOrderedDictionary.Keys;
ICollection valueCollection = myOrderedDictionary.Values;
// Display the contents using the key and value collections
DisplayContents(keyCollection, valueCollection, myOrderedDictionary.Count);
Comments
I would probably define a custom type:
public class Entity
{
public DateTime Date { get; set; }
public int[] Elements { get; set; }
}
and use Linq with Entity[]. Here's an example with sorting:
var entities = new[]
{
new Entity
{
Date = new DateTime(2009, 12, 10)
},
new Entity
{
Date = new DateTime(2009, 12, 11)
},
new Entity
{
Date = new DateTime(2009, 12, 9)
}
};
Array.Sort(entities, (e1, e2) => e1.Date.CompareTo(e2.Date));
1 Comment
LBushkin
I think this is a reasonable and appropriate approach. While
DataTables and multidimensional arrays can sometimes be appropriate, they are not a general substitute for meaningful model classes.