Reputation: 784
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?
Upvotes: 4
Views: 5030
Reputation: 28586
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);
Upvotes: 3
Reputation: 1038710
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));
Upvotes: 0
Reputation: 11264
You can use KeyValuePair<DateTime, int>
as an element type for your purpose.
Upvotes: 0
Reputation: 17949
A DataTable
would be far more appropriate for the operations you require, as it provides built-in support for sorting by column and other table-like operations.
Upvotes: 2