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:
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?
CodePudding user response:
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);
if (timeOffWithExpiration != null)
{
var TimeOff = new TimeOffApproved()
{
ExpirationDate = timeOffWithExpiration.Any() ? timeOffWithExpiration.First().Key : new DateTime()
};
}