Stuart
Stuart

Reputation: 143

combine two dd/mm/yyy string arrays into one while having the dates in order asp.net c#

I am calling two fields from two datatables (IncDate and ExpDate). They are stored as dd/MM/yyyy and when I make my sql call to the database, I use Order by Convert(DATETIME, IncDate, 103) to have the dates in order. I do this for each of my IncDate and ExpDae columns. I add each of these into a string array by using:

 var stringArr = Dt.AsEnumerable().Select(r => r.Field<string>("IncDate")).ToArray();
var stringArr2 = Dt2.AsEnumerable().Select(r => r.Field<string>("ExpDate")).ToArray();

The problem comes when I try to merge the two together into one string array. I do this by using:

string[] combined = stringArr.Concat(stringArr2).ToArray();

although this is just adding the dates randomly. I would like to have the dates combined and ordered in the combined string but I'm not sure how to do this.

So for example in IncDate I might have (01/03/2016, 02/03/2016, 03/03/2016, 06/03/2016) and in ExpDate i might have (02/03/2016, 03/03/2016, 04/03,2016) and when I combine them they should be in the order (01/03/2016, 02/03/2016, 02/03/2016, 03/03/2016, 03/03/2016, 04/03/2016, 06/03/2016)

Cheers in advance!

Upvotes: 1

Views: 128

Answers (1)

Heinzi
Heinzi

Reputation: 172478

  1. You already have a CONVERT statement in your ORDER BY clause to convert the string-date to a real date. Use the same CONVERT statement in your SELECT clause.

  2. Read the values as DateTimes instead of Strings:

     var dateArr = dt.AsEnumerable().Select(r => r.Field<DateTime>("IncDate")).ToArray();
    
  3. After concatenating the arrays, use OrderBy(x => x) or Array.Sort to sort it.

  4. Promise yourself to always use appropriate data types in your databases from now on instead of "hiding" dates in a string. That way, you won't need those CONVERT workarounds in the future.

General hint on working with "legacy" data stored in inappropriate data types: Convert the data to the real data type as soon as possible (note that we do that in Step 1), and, if required, convert it back as late as possible.

Upvotes: 3

Related Questions