Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pull a Dictionary Entry using Date only

I have a dictionary of type Dictionary<DateTime, Cars>

In the sample dictionary below, is it possible to pick out the value for june 2nd using the date only as the Key?

 [0]: {[{31-May-2022 6:12:30 AM}, {Cars}]}
 [1]: {[{01-Jun-2022 8:52:10 AM}, {Cars}]}
 [2]: {[{02-Jun-2022 6:19:17 AM}, {Cars}]}
 [3]: {[{03-Jun-2022 6:27:39 AM}, {Cars}]}
 [4]: {[{04-Jun-2022 6:47:00 AM}, {Cars}]}

thanks!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you already have a Dictionary that was created without that definition of "equality", then the best you can do is iterate through the keys.

You could alternatively create the dictionary with a IEqualityComparer<DateTime> class that defines "equality" as looking at the date only:

class DateEqualityComparer : IEqualityComparer<DateTime>
{
    public bool Equals(DateTime d1, DateTime d2)
    {
        if(d1.Date == d2.Date)
            return true;
        else
            return false;
    }

    public int GetHashCode(DateTime d)
    {
        return d.Date.GetHashCode();
    }
}

Note that:

  • This class would need to be used to create the dictionary; it could not be used after the fact
  • It would prevent the dictionary from having multiple DateTime key values with the same date; Adding a key with the same date but a different time would create a collision
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading