0

Using LINQ, I'm trying to select unique Customer's as Person objects. I'm using JSON data in the following example but I'm working with POCO objects in C#. In this example, I chose JSON to keep things simple.

I have the following Customer list:

[
  {
     "id": 123,
     "name: "John Smith",
     "transactionDate": "2019-08-21T10:30",
     "amount": 8.50
  },
  {
     "id": 234,
     "name: "Jane Doe",
     "transactionDate": "2019-08-22T18:21",
     "amount": 75.00
  },
  {
     "id": 123,
     "name: "John Smith",
     "transactionDate": "2019-08-26T10:30",
     "amount": 10.00
  }
]

I want to get the unique customers as Person objects and the result, should look like this:

[
  {
     "id": 123,
     "name": "John Smith"
  },
  {
     "id": 234,
     "name": "Jane Doe"
  }
]

The following should give me the unique ID's.

var uniqueIds = customers.Select(x => x.id).Distinct();

How do I now extract unique Person's from List<Customer>()?

Sam
  • 26,817
  • 58
  • 206
  • 383

2 Answers2

1

One way is to use GroupBy:

var uniquePersons = customers
    .GroupBy(c => new Person() {Id = c.Id, Name = c.Name})
    .Select(g => g.Key)
    .ToList();
Zohar Peled
  • 79,642
  • 10
  • 69
  • 121
  • This is a duplicate: https://stackoverflow.com/questions/489258/linqs-distinct-on-a-particular-property – aloisdg Aug 27 '19 at 06:40
  • @aloisdg I'm not sure it's an exact duplicate, but yes, the answers to the question you suggested can probably help the OP to solve their problem. – Zohar Peled Aug 27 '19 at 06:42
  • This got me close but didn't work. I updated the original post that shows what worked. – Sam Aug 27 '19 at 17:05
1

The suggested answer or the other SO post didn't return the results I needed. Here's the code that worked.

var uniquePersons = customers
                        .Select(x => new Person() { Id = x.Id, Name = x.Name })
                        .GroupBy(g => g.Id)
                        .Select(x => x.First())
                        .ToList();

I'm not saying this is the best way but this is what gave me a unique list of Person from a list of Customer.

I'd love to hear suggestions or explanations whether this is the best way to handle it or why the suggested answer didn't produce a List<Person>() with unique persons.

Sam
  • 26,817
  • 58
  • 206
  • 383