从列表C#中获取唯一的3位数拉链

ice*_*x19 3 .net c# regex

我有一个代表美国邮政编码的整数列表,我希望根据邮政编码的前三位数得到唯一值.例如,这是我的列表:

10433
30549
10456
54933
60594
30569
30659
Run Code Online (Sandbox Code Playgroud)

我的结果应仅包含:

10433
30549
54933
60594
30659
Run Code Online (Sandbox Code Playgroud)

从我的列表中排除的美国邮政编码是:1045630659,因为我已经有包含104xx和306xx的ZIP.

我真的不知道怎么做到这一点,我想这并不难,但我不知道.我已经创建了一个函数,它为我保存了前三位数字,并且我在每个zip的末尾添加了一些随机的2位数字.但它没有成功,因为我得到了例如10423但10423不在我的列表中,并且我没有特定的模式,我的所有数字都有一个范围内的最后2位数.

p.s*_*w.g 12

一点Linq应该工作.如果使用ints 列表:

var zips = new[] { 10433, 30549, 10456, 54933, 60594, 30569, 30659 };
var results = zips.GroupBy(z => z / 100).Select(g => g.First());
Run Code Online (Sandbox Code Playgroud)

或者如果使用strings 列表:

var zips = new[] { "10433", "30549", "10456", "54933", "60594", "30569", "30659" };
var results = zips.GroupBy(z => z.Remove(3)).Select(g => g.First());
Run Code Online (Sandbox Code Playgroud)

另一种解决方案是使用自定义IEqualityComparer<T>.对于ints:

class ZipComparer : IEqualityComparer<int> {
    public bool Equals(int x, int y) {
        return x / 100 == y / 100;
    }
    public int GetHashCode(int x) {
        return x / 100;
    }
}
Run Code Online (Sandbox Code Playgroud)

对于strings:

class ZipComparer : IEqualityComparer<string> {
    public bool Equals(string x, string y) {
        return x.Remove(3) == y.Remove(3);
    }
    public int GetHashCode(string x) {
        return x.Remove(3).GetHashCode();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后使用它,你可以简单地调用Distinct:

var result = zips.Distinct(new ZipComparer());
Run Code Online (Sandbox Code Playgroud)

最后,您还使用MoreLINQDistinctBy扩展方法(也可在NuGet上使用):

var results = zips.DistinctBy(z => z / 100);
// or
var results = zips.DistinctBy(z => z.Remove(3));
Run Code Online (Sandbox Code Playgroud)