[英]Get distinct items by combination from list C#
我的对象就像这样
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
我该如何解决这个问题?
您需要使用GroupBy
var result = regionsData.GroupBy(p => new {p.WfRegion, p.City})
.Select(g => g.First())
.ToList();
这将为您提供区域和城市的分组,然后您可以选择每个组中的第一个项目。
您可以使用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));
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.