Stalo Hadjitofi
Stalo Hadjitofi

Reputation: 15

Grouping common data into new string with LINQ C#

Basically, I have a list of objects - events containing these string fields:

Date:
Event_Name: 
Event_Time:
Event_Place:

Of course, some events are occurring at the same day and this is where my problem comes in:

I want to group the events that share the same date (key) together and create a new string which will contain all of the events on that same date.

Example:

Before:

Object 1:

Date: 2020/11/27
Event_Name: Dinner
Event_Time: 5pm
Event_Place: Johhny’s

Object 2:

Date: 2020/11/27
Event_Name: Dentist
Event_Time: 11am
Event_Place: Street 15

After Grouping:

Object:

Date: 2020/11/27
Event_Name: Dinner Dentist
Event_Time: 5pm 11am
Event_Place: Johhny’s Street 15

I tried using LINQ to group them - which worked but not the way I wanted to - it grouped them together hut it didnt “save” them as one string.

Is there any way I can do that?

Upvotes: 0

Views: 52

Answers (2)

Harald Coppoolse
Harald Coppoolse

Reputation: 30454

Of course this is possible using one of the overloads of Enumerable.GroupBy. Use the overload with parameter resultSelector:

// make groups of events where every event in the group has the same date:
var result = allEvents.GroupBy(event => event.Date,

    // parameter resultSelector: take every Date, and all events on this date to make
    // one new:
    (date, eventsOnThisDate) => new
    {
        Date = date,
        Names = String.Join(' ', eventsOnThisDate.Select(event => event.Event_Name)),
        Times = String.Join(' ', eventsOnThisDate.Select(event => event.Event_Time)),
        Places = String.Join(' ', eventsOnThisDate.Select(event => event.Event_Place)),
    });

However, are you sure you want this? You won't be able to see where / when every event will take place. Wouldn't it be more useful to have per date all events on this date, and per event the time / name / place?

// parameter resultSelector:
(date, eventsOnThisDate) => new
{
     Date = date,
     EventsOnThisDate = eventsOnThisDate.Select(event => new
     {
         Time = event.event_Time,
         Name = event.event_Name,
         Place = event.event_Place,
     })
     .ToList(),
});

Upvotes: 0

Prateek Shrivastava
Prateek Shrivastava

Reputation: 1937

This should work:

var grpByDate = allEvents.GroupBy(e => e.Date).Select(e =>
new Event
{
  Date = e.Key,
  Event_Name = string.Join(" ", e.SelectMany(x => x.Event_Name)),
  Event_Time = string.Join(" ", e.SelectMany(x => x.Event_Time)),
  Event_Place = string.Join(" ", e.SelectMany(x => x.Event_Place)),
});

Upvotes: 1

Related Questions