1

I have a text file imported and stored in a string array which looks like:

firstname, lastname, middlename, D/O/B, gender    
firstname, lastname, middlename, D/O/B, gender    
firstname, lastname, middlename, D/O/B, gender

etc etc etc

I want to sort the file by the DOB (studentFile[3]) but cannot get the app to read the array by datetime. This is what I have so far

var dateOrder = studentFile.OrderByDescending(x => DateTime.Parse(x.Split(',')[4]));
foreach (var date in dateOrder)
{
    Console.WriteLine("\t" + date);
}

Any ideas on where I'm going wrong and how to correct it?

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
ajm
  • 101
  • 2
  • 3
  • 15
  • 4
    You are accessing value at index 4. Shouldn't it be at index 3? – Rohit Vats Nov 30 '13 at 15:30
  • @RohitVats agree, that's the issue - arrays in C# are zero-based – Sergey Berezovskiy Nov 30 '13 at 15:31
  • As noted by rohit it seems index is wrong, what happens? You get an expection? – Sriram Sakthivel Nov 30 '13 at 15:31
  • I can't believe I missed that, even used [3] on my question haha, thanks anyway guys! – ajm Nov 30 '13 at 15:35
  • Depending on the size of your input data, and the amount you're applying this sorting, it might be wiser to choose for an approach that doesn't require splitting every string only to use one specific substring. This could be using a chained `.IndexOf` call, or splitting it once then storing it in a different data structure. For chaining see [this answer](http://stackoverflow.com/a/4578768/613176). – Aidiakapi Nov 30 '13 at 17:24

2 Answers2

0

Index on the result of the x.Split(',') should be 3, not 4

Moho
  • 15,457
  • 1
  • 30
  • 31
0

First, put your index to 3. Second, try to explicitly decalre your datetime array:

DateTime[] dateOrder = studentFile.OrderByDescending(x => DateTime.Parse(x.Split(',')[3]));
foreach (DateTime date in dateOrder)
    {
         Console.WriteLine("\t" + date.ToString());
    }
Grigory Kornilov
  • 366
  • 2
  • 4
  • 17