使用Lambda获取不同的父项 [英] Get Distinct Parent Items using Lambda

查看:63
本文介绍了使用Lambda获取不同的父项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下三个课程;

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 ?

推荐答案

您可以使用:

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

此列表没有区别.要使国家/地区唯一,您可以覆盖Country中的Equals + GetHashCode,为Enumerable.Disinct实现自定义IEqualityComparer<Country>或使用GroupBy(最慢但最简单的选项):

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):

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与它的实例一起使用:

Now you can use Distinct with an instance of it:

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

这篇关于使用Lambda获取不同的父项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆