C#: Get distinct values from list c#

Suppose we have a City class:

public class City
    {
        public string CityName { get; set; }
        public string CityKey { get; set; }
    }

Let's create a List of cities as shown:
     List<City> cities = new List<City>();
            cities.Add(new City { CityKey = "101", CityName = "London" });
            cities.Add(new City { CityKey = "102", CityName = "New York" });
            cities.Add(new City { CityKey = "101", CityName = "London" });
            cities.Add(new City { CityKey = "103", CityName = "Washington" });

As can be seen the City with name London and Key 101 is present more than once. If we want the distinct list of cities, we can get that using GroupBy as follows:

var distinctCities = cities.GroupBy(c => c.CityKey).Select(g => g.First()).ToList();
            foreach (var city in distinctCities)
            {
                Console.WriteLine("City Key: {0}, City Name: {1}", city.CityKey, city.CityName);
            }

Here we are first grouping the cities using the CityKey and then picking up the first only.


profile for Nadeem Yousuf at SharePoint Stack Exchange, Q&A for SharePoint enthusiasts

+