0

I'm trying to loop through a list (csv) containing two fields; a name and a date. There are various duplicated names and various dates in the list. I'm trying to deduce for each name in the list, where there are multiple instances of the same name, which corresponding date is the latest.

I realise, from looking at another answer, that I need to use the DateTime.Compare method which is fine, but my problem is working out which date is later. Once I know this I need to produce a file with unique names and the latest date relating to it.

This is my first question which makes me a newbie.

EDIT:

Initially I thought it would be 'ok' to set the LatestDate object to a date that wouldn't show up in my file, therefore making any later dates in the file the LatestDate.

Here's my coding so far:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace flybe_overwriter
{
class Program
{
    static DateTime currentDate;
    static DateTime latestDate = new DateTime(1000,1,1);
    static HashSet<string> uniqueNames = new HashSet<string>();

    static string indexpath = @"e:\flybe test\indexing.csv";
    static string[] indexlist = File.ReadAllLines(indexpath);
    static StreamWriter outputfile = new StreamWriter(@"e:\flybe test\match.csv");

    static void Main(string[] args)
    {

        foreach (string entry in indexlist)
        {

            uniqueNames.Add(entry.Split(',')[0]);

        }

        HashSet<string>.Enumerator fenum = new HashSet<string>.Enumerator();
        fenum = uniqueNames.GetEnumerator();

        while (fenum.MoveNext())
        {
            string currentName = fenum.Current;


            foreach (string line in indexlist)
            {
                currentDate = new DateTime(Convert.ToInt32(line.Split(',')[1].Substring(4, 4)), 
                                           Convert.ToInt32(line.Split(',')[1].Substring(2, 2)), 
                                           Convert.ToInt32(line.Split(',')[1].Substring(0, 2)));

                if (currentName == line.Split(',')[0])
                { 
                    if(DateTime.Compare(latestDate.Date, currentDate.Date) < 1)
                    {
                      //  Console.WriteLine(currentName + " " + latestDate.ToShortDateString() + " is earlier than " + currentDate.ToShortDateString());
                    }
                    else if (DateTime.Compare(latestDate.Date, currentDate.Date) > 1)
                    {
                     //   Console.WriteLine(currentName + " " + latestDate.ToShortDateString() + " is later than " + currentDate.ToShortDateString());
                    }
                    else if (DateTime.Compare(latestDate.Date, currentDate.Date) == 0)
                    {
                     // Console.WriteLine(currentName + " " + latestDate.ToShortDateString() + " is the same as " + currentDate.ToShortDateString());
                    }

                }
            }

        }


    }
}

}

Any help appreciated. Thanks.

Taniq
  • 178
  • 1
  • 11
  • 1
    "I realise, from looking at another answer, that I need to use the DateTime.Compare method " Umm... which answer? Do you have a link? Why can't you just use `dt1.Date < dt2.Date`? But I think this would be nicer rewritten using LINQ. – Mark Byers Jun 07 '12 at 09:35
  • I am not sure what you are looking for. You are saying "my problem is working out which date is later", but your code already does work that out. Could you please update your question text to make the actual question/problem more obvious? – O. R. Mapper Jun 07 '12 at 09:35
  • 1
    FYI; `StreamWriter` is best placed in a using-statement to ensure it is removed from memory when no longer needed. [link](http://www.dotnetperls.com/streamwriter) – Paul C Jun 07 '12 at 09:37
  • but if you purpose is just to deduce all the duplicate name why have you written that much of code? it can be done much simpler than that – 1Mayur Jun 07 '12 at 09:44
  • 1
    @MarkByers [I found this answer on stackoverflow](http://stackoverflow.com/questions/683037/how-to-compare-dates-in-c-sharp). – Taniq Jun 07 '12 at 09:49

1 Answers1

2

all in one, use the Max() function on your Datetimes instead making your own test.

var result = indexList
        //"transform" your initial list of strings into an IEnumerable of splitted strings (string[])
        .Select(list => list.Split(','))
        //in this new List of string[], select the first part in text, select and Convert the second part in DateTime. 
        //We now have an IEnumerable of anonymous objects, composed of a string and a DateTime Property
        .Select(splittedList => new
                                    {
                                        text = splittedList[0],
                                        date = new DateTime(Convert.ToInt32(splittedList[1].Substring(4, 4)),
                                                            Convert.ToInt32(splittedList[1].Substring(2, 2)),
                                                            Convert.ToInt32(splittedList[1].Substring(0, 2)))
                                    })
        //group that new List by the text Property (one "entry" for each distinct "text"). 
        //GroupBy creates an IGrouping<out TKey, out TElement>, kind of special dictionary, with an IEnumerable<TResult> as "value" part 
        //(here an IEnumerable of our anonymous object)
        .GroupBy(textDateTimeList => textDateTimeList.text)
         //from this grouping, take the "key" (which is the "distinct text", and in the IEnumerable<anonymousObject>, take the Max Date. 
         //We now have a new List of anonymous object, with a string Property and a DateTime Property
        .Select(group => new
                             {
                                 stringField = group.Key,
                                 maxDateField = group.Max(dateField => dateField.date)
                             });
Raphaël Althaus
  • 59,727
  • 6
  • 96
  • 122
  • Ok. Going to have to a look at this one and see what results I get. Thanks. – Taniq Jun 07 '12 at 10:06
  • So. I've implemented this coding and it works really well... haven't got a clue as to HOW it works yet as I've never seen script like this before (hell I really feel like a newbie now...) Thanks again. – Taniq Jun 07 '12 at 10:17
  • Well, then welcome in linq, I tried to comment a bit if it helps... but more reading will be needed. – Raphaël Althaus Jun 07 '12 at 11:44
  • Thanks for you comments and taking the time to write. So much easier than what I was trying! – Taniq Jun 07 '12 at 12:43