c# - 使用 Lambda 获取不同的父项

标签 c# linq list lambda distinct

我有以下三个类(class);

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; }
}

我已填充一个城市列表对象以包含多个城市,其中每个城市都有一个地区和一个国家/地区。

现在我想获取所有国家/地区所有城市的列表。我尝试过以下方法;

List<City> CityObjectList = GetAllCity();
CityObjectList.Select(r => r.Region).ToList().Select(c => c.Country).ToList();

但是,我返回的只是所有国家/地区。我怎样才能获得不同的国家/地区?

最佳答案

您可以使用:

var allCityCountries = CityObjectList.Select(c => c.Region.Country).ToList();

这个列表并不明确。要使国家/地区独一无二,您可以覆盖 Equals + GetHashCodeCountry ,实现自定义IEqualityComparer<Country>对于 Enumerable.Disinct或使用GroupBy (最慢但最简单的选择):

var distinctCountries = CityObjectList
    .Select(c => c.Region.Country)
    .GroupBy(c => c.CountryCode)
    .Select(g => g.First())
    .ToList();

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();
    }
}

现在您可以使用Distinct及其实例:

var comparer = new CountryCodeComparer();
distinctCountries = CityObjectList.Select(c => c.Region.Country).Distinct(comparer).ToList();

关于c# - 使用 Lambda 获取不同的父项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29146355/

相关文章:

c# - Linq 中的相关子查询

linq - 如何使用 LINQ 选择最小子序列?

python - 如何在句子列表中的单词和左括号之间创建空格

c# - 齐次线性方程组的基本解 : Ax=0 with Det(A)=0 with MathNet

c# - 如果类是 WinRT 类型,如何使用 C# 反射来确定

c# - 如何在不实例化它们的情况下测试两个泛型是否具有基子类关系?

python - 在python中,如何获取对象/字典列表中的最低键值对,其中每个项目都有不同的、单独的键值对?

c# - NHibernate + ActiveRecord + PostgreSQL = 内存异常

c# - 具有泛型类属性的 LINQ 表达式

python - 将 1 个两个元组的列表或列表列表传递到 scipy interp1d 函数