从列表中通过组合获取独特项 C#

5
我的对象长这个样子
    public class Region
{
    public Region();

    public string City { get; set; }
    public int PostCode { get; set; }
    public string WfRegion { get; set; }
}

我有一个类中的对象列表,其中数据如下:
Rodney , 7845 , Auckland
Rodney , 3435 , Auckland
Rodney , 4566 , Auckland
Rodney , 3445 , North Island

我想筛选这个列表,以便获得以下输出。
    Rodney , 7845 , Auckland
    Rodney , 3445 , North Island

无论邮政编码如何,都需要列出城市和地区的所有可能组合。

我写了一些类似于以下的查询:

      var cities = regionsData.DistinctBy(p => 
p.WfRegion).DistinctBy(p=>p.PostCode).DistinctBy(p => p.City).ToList();

但是这样只会返回第一个元素的结果,如下所示:
        Rodney , 7845 , Auckland

我该如何解决这个问题?

2个回答

7

你需要使用GroupBy函数

var result = regionsData.GroupBy(p => new {p.WfRegion, p.City})
    .Select(g => g.First())
    .ToList();

那样可以按区域和城市进行分组,然后您只需选择每个组中的第一项。

0
你可以使用 DistinctBy 来解决这个问题,具体如下:
var cities = regionsData.DistinctBy(x => (x.City, x.WfRegion));

请注意,这是使用C#7元组语法。对于旧版本,您必须使用匿名类型,如下所示:
var cities = regionsData.DistinctBy(x => new {x.City, x.WfRegion});

完整的控制台示例:

using System;
using System.Collections.Generic;
using MoreLinq;

namespace ConsoleApp1
{
    public class Region
    {
        public string City     { get; set; }
        public int    PostCode { get; set; }
        public string WfRegion { get; set; }

        public override string ToString()
        {
            return  $"City:{City}, PostCode:{PostCode}, WfRegion:{WfRegion}";
        }
    }

    class Program
    {
        static void Main()
        {
            IEnumerable<Region> regions = new []
            {
                new Region { City = "CityOne", PostCode = 1, WfRegion = "WfRegionOne"},
                new Region { City = "CityOne", PostCode = 2, WfRegion = "WfRegionTwo"},
                new Region { City = "CityTwo", PostCode = 3, WfRegion = "WfRegionOne"},
                new Region { City = "CityOne", PostCode = 4, WfRegion = "WfRegionOne"},
                new Region { City = "CityOne", PostCode = 5, WfRegion = "WfRegionThree"},
                new Region { City = "CityTwo", PostCode = 6, WfRegion = "WfRegionOne"},
                new Region { City = "CityTwo", PostCode = 7, WfRegion = "WfRegionThree"}
            };

            var result = regions.DistinctBy(x => (x.City, x.WfRegion));

            Console.WriteLine(string.Join("\n", result));
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接