Search code examples
asp.netlinqasp.net-mvc-4c#-4.0entity-framework-4

How can i retrieve a distinct list in Linq?


I Want My result like this

McLaren Cup
       The Regis Brunch
                  21st Jan 2017
                  24st Jan 2017
                  26st Jan 2017
       General Entry
       General Parking
        Picnic Parking
                  21st Jan 2017
                  24st Jan 2017
                  26st Jan 2017

For this i did LINQ query , But am getting exception as follows Additional information: The 'Distinct' operation cannot be applied to the collection ResultType of the specified argument.

  var Ticketdata = (from Tevent in context.TicketEventsMaster
  where Tevent.IsActive == true && Tevent.IsVisible == true
  select new
  {
    EventID = Tevent.TicketEventID,
    eventName = Tevent.TicketEventName,
    EventCategories = (from TEM in context.TicketCategoriesMaster
       join TED in context.TicketEventDates on TEM.CategoryID equals TED.TCategoryID
       where TED.IsActive == true && TED.IsVisible == true && TED.TEventID == Tevent.TicketEventID
       //orderby TED.DisplayOrder
       select new
      {
          CategoryID = TED.TCategoryID,
          CategoryName = TEM.CategoryName,
          EventDates = (from tDate in context.TicketEventDates
            where
              tDate.IsActive == true && tDate.IsVisible == true
              && tDate.TEventID == Tevent.TicketEventID
              && tDate.TCategoryID == TEM.CategoryID
            orderby tDate.TEventDate
            select new
            {
              DateID = TED.ID,
              Dates = TED.TEventDate != null ? TED.TEventDate.ToString() : string.Empty,
              Times = TED.TEventTime != null ? TED.TEventTime.ToString() : string.Empty,
            }).ToList()
      }).Distinct().ToList()

  }).ToList();

Solution

  • There is lots of ways to get Distinct data. you can use "DistinctBy" with deisred properties or you can use

     var result = table.GroupBy(test => test.id)
                       .Select(grp => grp.First())
                       .ToList();