从列表C#中获取组合的不同项

时间:2017-05-01 11:39:57

标签: c# asp.net linq

我的对象就像这样

    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 个答案:

答案 0 :(得分:7)

您需要使用GroupBy

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

这将为您提供区域和城市的分组,然后您可以选择每个组中的第一个项目。

答案 1 :(得分: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));
        }
    }
}