I have the following three classes;
public class City
{
public int CityId { get; set; }
public Region Region { get; set; }
public string Name { get; set; }
}
public class Region
{
public int RegionId { get; set; }
public Country Country { get; set; }
public string Name { get; set; }
}
public class Country
{
public string CountryCode { get; set; }
public string Name { get; set; }
}
I have populated a City List object to contain a number of cities, of which each have a Region and a Country.
Now I want to get a list of all countries for all cities. I've tried the following;
List<City> CityObjectList = GetAllCity();
CityObjectList.Select(r => r.Region).ToList().Select(c => c.Country).ToList();
However, all I get back is all the countries. How can I get the distinct countries ?
You can use:
This list is not distinct. To make the countries unique you could either override
Equals
+GetHashCode
inCountry
, implement a customIEqualityComparer<Country>
forEnumerable.Disinct
or useGroupBy
(slowest but easiest option):The
IEqualityComparer<T>
way:Now you can use
Distinct
with an instance of it: