Tuesday, October 29, 2013

Linq to get Duplicate Values from a list

void Main()
{
       //int[] listOfItems = new[] { 4, 2, 3, 1, 6, 4, 3 };
       List<Hotel> listOfItems = new List<Hotel>();
       listOfItems.Add(new Hotel(){ name="Hotel1"});
       listOfItems.Add(new Hotel(){ name="Hotel2"});
       listOfItems.Add(new Hotel(){ name="Hotel3"});
       listOfItems.Add(new Hotel(){ name="Hotel3"});
       listOfItems.Add(new Hotel(){ name="Hotel4"});
       listOfItems.Add(new Hotel(){ name="Hotel1"});
       listOfItems.Add(new Hotel(){ name="Hotel4"});
      
       var duplicates = listOfItems
           .GroupBy(i => i.name)
           .Where(g => g.Count() > 1)
           .Select(k => k.Key);
      
       Console.WriteLine(duplicates.Count());
      
       foreach (var d in duplicates)
           Console.WriteLine(d);
}

class Hotel
{
public string name;
}



No comments:

Post a Comment