Robert Ross
Robert Ross

Reputation: 1189

Cannot implicitly convert time type System.TimeSpan to 'long'

So I've got the following query :

var a = from x in list
        group x by new { x.fname, x.lname } into g
        select new RolesUsersViewModel(g.Key.fname, 
                                       g.Key.lname, 
                                       g.Sum(x => x.FocusEnd - x.FocusStart)
                                      );

I got the error, which is on the title of this question in this part : x => x.FocusEnd - x.FocusStart

FocusEnd and FocusStart are of type DateTime. Can somebody help? I am new to c# and not sure how to deal with this in an adequate way.

Here is the code for the ViewModel.

public class RolesUsersViewModel
    {
        public RolesUsersViewModel(string FirstName, string LastName, TimeSpan totalex)
        {
            fname = FirstName;
            lname = LastName;
            total = totalex;
        }
        public string fname { get; set; }
        public string lname { get; set; }
        public TimeSpan total { get; set; }

    }

Upvotes: 3

Views: 2303

Answers (3)

Tim Schmelter
Tim Schmelter

Reputation: 460168

The result of a subtraction of two DateTimes is a TimeSpan. Unfortunately you can't Sum timespans. You could sum their TotalMilliseconds and create a new TimeSpan with TimeSpan.FromMilliseconds:

....
select new RolesUsersViewModel(
               g.Key.fname, 
               g.Key.lname, 
               TimeSpan.FromMilliSeconds(g.Sum(x => (x.FocusEnd - x.FocusStart).TotalMilliseconds)));

Upvotes: 5

Jeroen van Langen
Jeroen van Langen

Reputation: 22073

You could temporarly add them as seconds or ticks

TimeSpan.FromSeconds( g.Sum(x => x.FocusEnd.TotalSeconds - x.FocusStart.TotalSeconds))

Upvotes: 3

Set
Set

Reputation: 49789

This is cause Timestamp - Timestamp = Timestamp. If you want to sum ticks, do

Sum(x => (x.FocusEnd - x.FocusStart).Ticks)

or for seconds

Sum(x => (x.FocusEnd - x.FocusStart).TotalSeconds)

Upvotes: 3

Related Questions