简体   繁体   中英

Get list of objects with unique combination of id/values

I have this collection:

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

I would like to get a list of objects containing an ID and postalcode. The ID may occur multiple times, but the postalcode should be unique PER id.

So my result would be:

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

This is my query:

collection.Select(x => new

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

I'm stuck in how to flatten the postalcodes so each postal code would create a seperate object.

Thanks!

I think you mean:

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

Or in LINQ language terms:

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

The SelectMany expands an inner collection, giving us all the Id / postalcode pairs; then the Distinct collapses them to the uniques.

Which gives:

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

For the data, I'm using:

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

you can use SelectMany to flattern inner collections, ie:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM