rectoplasmus
rectoplasmus

Reputation: 19

Get total time duration by group from list

I have this list "userLoginTrials" and have to do the following:

Simple: I have to get the total login-duration of every User in the list.

Upvotes: 0

Views: 77

Answers (3)

DavidG
DavidG

Reputation: 118957

This should do the job (note that I used the none underscored versions of your variables as I assume they are private to your class):

var data = from u in userLoginTrials
           where u.LogoutTimeStamp != null
           group u by u.UserId into g
           select new
           {
               UserId = g.Key,
               TotalTime = g.Sum(t => t.LogoutTimeStamp - t.TrialTimeStamp)
           };

Upvotes: 3

Christos
Christos

Reputation: 53958

You could try something like the following one:

var output = userLoginTrials.GroupBy(x=>x.UserId)
                            .Select(x=>new {
                                UserId = x.Key,
                                TotalDuration = x.Where(y=>y.LogoutTimeStamp!=null)
                                                 .Sum(y=>(y.LogoutTimeStamp-y.TrialTimeStamp))
                            });

Initially, we make a group by of the objects inside the userLoginTrials list. Then, for each created group we create a projection to an anonymous type with properties, one would be the Key of the group, the UserId and the other the TotalDuration of the User. In order we achieve the latter, we filter the elements of the group, in order to get the elements with LogoutTimeStamp not equal to null. Then we sum for all of these elements the difference between the LogoutTimeStamp and TrialTimeStamp.

update

As DavidG correctly pointed out in the comments a better approach would be the following one:

var output = userLoginTrials.Where(x=>x.LogoutTimeStamp!=null)
                            .GroupBy(x=>x.UserId)
                            .Select(x=>new {
                                UserId = x.Key,
                                TotalDuration = x.Sum(y=>(y.LogoutTimeStamp-y.TrialTimeStamp))
                            });

This way you take only the items of userLoginTrials list that have a LogoutTimeStamp different from null and then you make the group by to these items.

Upvotes: 1

Lorcan O'Neill
Lorcan O'Neill

Reputation: 3393

var groups = userLoginTrials.GroupBy(u => u.UserId);
foreach(var group in groups)
{
    // group.Key is the UserId
    // group will contain an IEnumerable<UserLoginTrial> with that UserId
    foreach(var userLoginTrial in group)
    {
    // Add your logic here
    }
}

Upvotes: 0

Related Questions