开发者

Joining items in a single List<>

开发者 https://www.devze.com 2023-03-11 17:28 出处:网络
I have a list of custom objects called EntertainmentEvent: public class EntertainmentEvent { public string Title { get; set; }

I have a list of custom objects called EntertainmentEvent:

public class EntertainmentEvent
{
    public string Title { get; set; }
    public string TagLine { get; set; }
    public string Overview { get; set; }
    public string ThumbnailUrl { get; set; }
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
    public string EventTime { get; set; }
    public Reoccurrence Reoccurrence { get; set; }
    public string Url { get; set; }
}

I'd like to merge items with the same StartDate together into a single EntertainmentEvent which has a title of the two merged items concatenated together.

So far I have this:

var duplicateDates = allEvents.Join
(
    allEvents, x => x.StartDate, y => y.StartDate,
    (x, y) => x.Title != y.Title 
    ? new EntertainmentEvent
    {
        Title = string.Format("{0}, {1}", x.Title, y.Title),
        StartDate = x.StartDate
    }
    : null
)
.Where(x => x != null)
.ToList();

The only problem with this method is that I get duplicated items - for a sinlge date , duplicateDates list will end up with two entries

Entry 1: Startdate = 1/1/2011, Title = "Item One Title, Item Two Title"

Entry 2: Startdate = 1/1/2011, Title = "Item Two Title, Item One Title"

I'm certain there's a开发者_如何学运维 better way of coding this but research has come up empty thus far.

Thanks :)


var result = allEvents
   .GroupBy(e => e.StartDate)
   .Select(gp => new EntertainmentEvent
                        {
                          Title = string.Join(", ", gp), 
                          StartDate = gp.Key 
                        });


Have u tried using group by StartDate? Then u can merge all listed items into one


The following will be close, though you'll need to add Null checking and all that.

class Comparer : IEqualityComparer <EntertainmentEvent>
{
   public bool Equals( EntertainmentEvent x, EntertainmentEvent y )
   {
       return x.Startdate == y.Startdate;
   }

   public int GetHashCode( EntertainmentEvent event )
   {
      return event.StartDate.GetHashCode();
   }

}

var duplicateDates = allEvents.Join
(
    allEvents, x => x.StartDate, y => y.StartDate,
    (x, y) => x.Title != y.Title 
    ? new EntertainmentEvent
    {
        Title = string.Format("{0}, {1}", x.Title, y.Title),
        StartDate = x.StartDate
    }
    : null
)
.Where(x => x != null)
.Distinct( new Comparer() )
.ToList();
0

精彩评论

暂无评论...
验证码 换一张
取 消