views:

276

answers:

4

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?

A: 

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.

Mike
A: 

You can use KeyValuePair<DateTime, int> as an element type for your purpose.

Li0liQ
A: 

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));
Darin Dimitrov
I think this is a reasonable and appropriate approach. While `DataTable`s and multidimensional arrays can sometimes be appropriate, they are not a general substitute for meaningful model classes.
LBushkin
+2  A: 

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);
serhio