Paul
Paul

Reputation: 217

Linq To Objects With DateTime Properties

If you have a collection of:

public class TestObj        
{        
    public DateTime Key { get; set; }
    public int MyProperty { get; set; }
    public int MyProperty2 { get; set; }
}

The collection might have a count of 20,000 TestObj objects. I need to query using linq on the Key (DateTime) from DateTime t1 to DateTime t2. I also want to insert and delete from the collection. I see that the SortedList has an Add and a Remove method. Is SortedList efficient way to handle this problem? I am thinking that a List<T> would have to traverse through the entire list to be sure of getting all objects with t1 and t2.

Upvotes: 0

Views: 168

Answers (1)

Alexander Mills
Alexander Mills

Reputation: 277

You should not worry too much about performance of lists. 20,000 is nothing. If you have a list with billions of elements, then it might be more of a problem, but even then, optimization causes more problems than it solves.

If you want to make sure it doesn't matter, you can test it yourself:

var l = new SortedList<DateTime, TestObj>();
var key = new DateTime(1995, 1, 1);
for (var i = 0; i < 20000; i++)
{
    var o = new TestObj();
    o.Key = key;
    key = key.AddDays(1);
    l.Add(o.Key, o);
}
var sw = new Stopwatch();
var date1 = new DateTime(1995, 5, 5);
var date2 = new DateTime(2010, 5, 5);
sw.Start();
var between = l.Where(x => x.Key >= date1 && x.Key <= date2).ToArray();
Console.WriteLine(between.Count());
sw.Stop();
Console.WriteLine(sw.Elapsed);

Output is:

5480 (number of elements filtered out) and 00:00:00.0142387 (you wouldn't even notice)

Upvotes: 2

Related Questions