获取具有唯一ID /值组合的对象列表

时间:2017-11-13 14:07:56

标签: c# entity-framework linq

我有这个系列:

{
  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()

我坚持如何压扁邮政编码,因此每个邮政编码都会创建一个单独的对象。

谢谢!

2 个答案:

答案 0 :(得分:3)

我认为你的意思是:

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 }
    }};

答案 1 :(得分:1)

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

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