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?

2
  • multidimentional? how do you want to sort it? Commented Dec 10, 2009 at 16:21
  • I think Ben meant a array of 2 columns, DateTime and int, like Dictionary<DateTime, int> Commented Dec 10, 2009 at 16:39

4 Answers 4

3

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);
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

0

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

Comments

0

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

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.