【问题标题】:Get list of objects with unique combination of id/values获取具有唯一 ID/值组合的对象列表
【发布时间】:2017-11-13 14:07:55
【问题描述】:

我有这个收藏:

{
  Id: 5,
  postalcodes: {2000, 3000, 4000}
}, 
{
 Id: 5,
 postalcodes: { 2000, 5000 }
},
{
 Id: 6,
 postalcodes: { 2000, 7000 }
}

我想获取包含 ID 和邮政编码的对象列表。 ID 可能出现多次,但邮政编码应该是唯一的 PER id。

所以我的结果是:

{
 id: 5,
 postalcode: 2000
}
{
 id: 5,
 postalcode: 3000
}
{ 
 id: 5,
 postalcode: 4000
}
{
 id: 5,
 postalcode: 5000
}
{
 id: 6,
 postalcode: 2000
}
{
 id: 6,
 postalcode: 7000
}

这是我的查询:

collection.Select(x => new

                                                                 {
                                                                     x.id,
                                                                     x.postalcodes
                                                                 })
    .Distinct()

我不知道如何展平邮政编码,以便每个邮政编码都会创建一个单独的对象。

谢谢!

【问题讨论】:

    标签: c# entity-framework linq


    【解决方案1】:

    我想你的意思是:

    var pairs = collection.SelectMany(x => x.postalcodes.Select(
            y => new { x.Id, postalcode = y })).Distinct();
    
    foreach(var pair in pairs)
    {
        Console.WriteLine($"{pair.Id}, {pair.postalcode}");
    }
    

    或者用 LINQ 语言 术语:

    var pairs = (from x in collection
                 from postalcode in x.postalcodes
                 select new { x.Id, postalcode }).Distinct();
    

    SelectMany 扩展了一个内部集合,为我们提供了所有 Id / postalcode 对;然后Distinct 将它们折叠成唯一的。

    这给出了:

    5, 2000
    5, 3000
    5, 4000
    5, 5000
    6, 2000
    6, 7000
    

    对于数据,我正在使用:

    var collection = new[] { new {
            Id = 5,
            postalcodes = new[] { 2000, 3000, 4000}
        },
        new {
            Id = 5,
            postalcodes = new[] { 2000, 5000 }
        },
        new {
            Id = 6,
            postalcodes = new[] { 2000, 7000 }
        }};
    

    【讨论】:

    • 这就是我到目前为止所尝试的,但我收到一个错误,告诉我邮政编码有歧义。我怀疑这是因为它是一个可为空的字段,因为我可以毫无问题地选择其他属性。
    • @Bv202 你从哪里得到的?我所展示的内容已编译并运行,因此很高兴看到更多上下文,以便我们为您提供帮助
    【解决方案2】:

    您可以使用SelectMany 来扁平化内部集合,即:

    collection
    .SelectMany(i => i.postalcodes.Select(j=>new{i.id, postalcode = j}))
    .Distinct()
    

    【讨论】:

    • 确实,我错过了 id 重复
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-18
    • 2015-03-08
    • 1970-01-01
    相关资源
    最近更新 更多