Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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; }

    }
like image 583
Robert Ross Avatar asked Dec 14 '25 21:12

Robert Ross


2 Answers

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)));
like image 155
Tim Schmelter Avatar answered Dec 16 '25 13:12

Tim Schmelter


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)
like image 30
Set Avatar answered Dec 16 '25 11:12

Set



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!