[英]Get Distinct Parent Items using Lambda
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: 您可以使用:
var allCityCountries = CityObjectList.Select(c => c.Region.Country).ToList();
This list is not distinct. 此列表不是唯一的。 To make the countries unique you could either override
Equals
+ GetHashCode
in Country
, implement a custom IEqualityComparer<Country>
for Enumerable.Disinct
or use GroupBy
(slowest but easiest option): 要使国家/地区唯一,您可以覆盖
Country
Equals
+ GetHashCode
,为Enumerable.Disinct
实现自定义IEqualityComparer<Country>
或使用GroupBy
(最慢但最简单的选项):
var distinctCountries = CityObjectList
.Select(c => c.Region.Country)
.GroupBy(c => c.CountryCode)
.Select(g => g.First())
.ToList();
The IEqualityComparer<T>
way: IEqualityComparer<T>
方式:
class CountryCodeComparer : IEqualityComparer<Country>
{
public bool Equals(Country x, Country y)
{
if(object.ReferenceEquals(x, y)) return true;
if(x == null || y == null) return false;
return x.CountryCode == y.CountryCode;
}
public int GetHashCode(Country obj)
{
return obj == null ? 0 : obj.CountryCode == null ? 0 : obj.CountryCode.GetHashCode();
}
}
Now you can use Distinct
with an instance of it: 现在,您可以将
Distinct
与它的实例一起使用:
var comparer = new CountryCodeComparer();
distinctCountries = CityObjectList.Select(c => c.Region.Country).Distinct(comparer).ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.