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

First statement did not work on dictionary result

I have a method that returns a dictionary as:

 public async Task<Dictionary<DateTime, double>> GetAvailableTimeOffWithExpiration(int userId)
        {
            ..../ code here

            Dictionary<DateTime, double> expirationDates = ...
            return expirationDates;
        }

Then I want to assign the first value of the dictionary to my DateTime variable of TimeOffApproved model as:

  var timeOffWithExpiration = await this.GetAvailableTimeOffWithExpiration(u.Id);
  var TimeOff = new TimeOffApproved()
                {
                    ExpirationDate = timeOffWithExpiration.First()
                };

But it is returning error:

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

Error CS0029: Cannot implicitly convert type
‘System.Collections.Generic.KeyValuePair<System.DateTime, double>’ to
‘System.DateTime’

Why is trying to assign the dictionary if I’m using the First() statement?

>Solution :

The First() method returns the first element of a collection in case of the Dictionary that is a KeyPair Value. To get date part you need to add .Value or .Key (depending on the part you need – in your case .Key) to the statement like this:

var timeOffWithExpiration = await this.GetAvailableTimeOffWithExpiration(u.Id);
var TimeOff = new TimeOffApproved()
{
   ExpirationDate = timeOffWithExpiration.First().Key
};

I would recommend a check to ensure that the first element is not null, like this for example (correction due to compiler error):

var timeOffWithExpiration = await this.GetAvailableTimeOffWithExpiration(u.Id);
var TimeOff = new TimeOffApproved()
{
    ExpirationDate = timeOffWithExpiration.Any() ? timeOffWithExpiration.First().Key : new DateTime()
};
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