sterix24
sterix24

Reputation: 2400

Using LINQ to build a new collection

At the moment I have a collection of 'Visit' classes. The Visit class has a number of properties but here are the relevant ones for my problem:

public class Visit 
{
  public int Id { get; set; }
  public DateTime VisitDate { get; set; }
  public int VisitDuration { get; set; }
  // Other irrelevant properties...  
}

I also have created a new class called 'VisitDuration':

public class VisitDuration
{
  public DateTime VisitDate { get; set; }
  public int Duration { get; set; }
{

I have a function which fetches a collection of visits between two dates like so:

var visits = GetVisitsCollection();

What I want to do is to group up the visits by VisitDate, and then create a new instance of the VisitDuration class which should contain the VisitDate and the average visit duration for that date.

So for example, if there were 3 visits occurring on the date 28/11/2014, with durations of 20, 40 and 60 respectively, I'd want to create a new instance of VisitDuration with VisitDate: 28/11/2014 and Duration: 40 (the average of the 3). How can I do this using linq?

I've done something similar using counts that uses GroupBy ie:

var collection = visits.GroupBy(v => v.VisitDate).Select(x => new 
            {
                VisitDate = x.Key.ToString(),
                Count = x.Count()
            });

But the difference is rather than getting the count, I want to get a value that's an average of a property of all records that have that VisitDate.

I hope I've explained myself well and appreciate any responses! Thanks

Upvotes: 0

Views: 97

Answers (1)

Rahul Singh
Rahul Singh

Reputation: 21795

Try this:-

var collection = visits.GroupBy(x => x.VisitDate)
                       .Select(x => new VisitDuration
                              {
                                  VisitDate = x.Key,
                                  Duration = Convert.ToInt32(x.Average(z => z.VisitDuration))
                              });

Working Fiddle.

Upvotes: 2

Related Questions