tags:

views:

138

answers:

2

01.02.2010 0:00:00 -> 01.02.2010 anytime

01.02.2010 0:00:00 -> 01.02.2010 0:any minutes and seconds

so here is my date :

 DateTime x;

it's 01.02.2010 0:00:00 as a string

 x.Date.ToString()

here I compare date

DatarowsForOneDay = dt.Select("DailyRecTime= '" + x.ToString() + "'");

So how can I group by date + Hours without care about minutes and seconds.

+2  A: 

You could write your own IEqualityComparer<DateTime> to only compare the parts of the DateTime you care about. LINQ's GroupBy has an overload that takes an IEqualityComparer. I had the same problem recently and did just that.

But you would have to call GroupBy before converting to strings. If you can't then you might want to create an IEqualityComparer<string> and parse the strings back to DateTime before comparing.

I don't have the original code with me right now. I re-typed this from memory and did not test it.


public class DateAndHourComparer : IEqualityComparer
{
    public bool Equals(DateTime x, DateTime y)
    {
        var xAsDateAndHours = AsDateHoursAndMinutes(x);
        var yAsDateAndHours = AsDateHoursAndMinutes(y);

        return xAsDateAndHours.Equals(yAsDateAndHours);
    }

    private DateTime AsDateHoursAndMinutes(DateTime dateTime)
    {
        return new DateTime(dateTime.Year, dateTime.Month, 
                            dateTime.Day, dateTime.Hour, 
                            dateTime.Minute, 0);
    }

    public int GetHashCode(DateTime obj)
    {
        return AsDateHoursAndMinutes(obj).GetHashCode();
    }
}

I never did the string based version, but it could use the above DateTime based code and look something like...


public class DateAndHourStringComparer : IEqualityComparer
{
    private readonly DateAndHourComparer dateComparer = new DateAndHourComparer();

    public bool Equals(string x, string y)
    {
        var xDate = DateTime.Parse(x);
        var yDate = DateTime.Parse(y);

        return dateComparer.Equals(xDate, yDate);
    }

    public int GetHashCode(string obj)
    {
        var date = DateTime.Parse(obj);
        return dateComparer.GetHashCode(date);
    }
}

I have not tested it, I did not add null checks or format checks. The code is meant to demonstrate the general idea.

Mike Two
can you share some example code ?
nCdy
+1  A: 

You can pass a parameter with DateTime.ToString(string pattern). More information @ http://www.geekzilla.co.uk/View00FF7904-B510-468C-A2C8-F859AA20581F.htm.

Fabian
but then how do you do the group by?
Mike Two
01.02.2010 0:00:00 = 01.02.2010 ... it works
nCdy