-2

Looking to convert a list of sessions:

public class Sessions
    {
        public int SessionId {get; set; }
        public string Date { get; set; }
        public string Time { get; set; }
    }

into a list of DateOut:

public class DateOut
    {
        public int SessionId { get; set; }
        public string Date { get; set; }
        public List<string> Times { get; set; }
    }

Looking a result of to show each date with their associated times..

New to LINQ and C# so any help on getting this result through LINQ or another more practical solution would be great

1 Answers1

1

I'm assuming you're after something like this:

List<DateOut> DateOutList = SessionList
    .GroupBy(s => new { s.SessionId, s.Date}, it => it.Time)
    .Select(s => new DateOut {
        SessionId = s.Key.SessionId,
        Date = s.Key.Date,
        Times = s.ToList()
    })
    .ToList();

This assumes your date string is just the date. If it includes time components, you could do something like this:

List<DateOut> DateOutList = SessionList
    .GroupBy(s => new { s.SessionId, Date = Convert.ToDateTime(s.Date).Date}, it => it.Time)
    .Select(s => new DateOut {
        SessionId = s.Key.SessionId,
        Date = s.Key.Date.ToString(),
        Times = s.ToList()
    })
    .ToList();

While this will work, if you're doing anything else with Date and Time, I would recommend converting them to DateTime fields.

greenjaed
  • 589
  • 8
  • 20
  • 1
    Small correction: `Times = s.Select(it => it.Time).ToList()` – alexm Jan 08 '21 at 00:36
  • Yes this looks spot on but I don't get the groupby part, it's showing an error for SessionId and Date on the second line as they don't exist in this context – Ciarán Conville Jan 08 '21 at 00:43
  • Okay, I edited my answer to be syntactically correct – greenjaed Jan 08 '21 at 00:46
  • Very close but with a list of 7 I am getting a result of a list of 7 with a date and a time in each. But what I am after is if there are two entries with the same date, these should be one result with the date string and the 2 times in a list – Ciarán Conville Jan 08 '21 at 00:57
  • It's the full time for now but I plan to truncate on the frontend, but for now the time part is just something like `"2021-01-13T00:00:00.000Z"` – Ciarán Conville Jan 08 '21 at 01:04
  • I added more to the answer. Knowing nothing about your data, that should get you the groupings you want. – greenjaed Jan 08 '21 at 01:39