简体   繁体   English

使用LINQ选择具有唯一ID的对象作为另一种对象类型

[英]Select objects with unique ID's as another object type using LINQ

Using LINQ , I'm trying to select unique Customer 's as Person objects. 使用LINQ ,我试图选择唯一的Customer作为Person对象。 I'm using JSON data in the following example but I'm working with POCO objects in C# . 在以下示例中,我使用JSON数据,但在C#使用POCO对象。 In this example, I chose JSON to keep things simple. 在此示例中,我选择了JSON来使事情保持简单。

I have the following Customer list: 我有以下Customer列表:

[
  {
     "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: 我想获得唯一的客户作为Person对象,其结果应如下所示:

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

The following should give me the unique ID's. 以下应该给我唯一的ID。

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

How do I now extract unique Person 's from List<Customer>() ? 现在如何从List<Customer>()提取唯一的Person

One way is to use GroupBy : 一种方法是使用GroupBy

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

The suggested answer or the other SO post didn't return the results I needed. 建议的答案或其他SO帖子未返回我需要的结果。 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 . 我并不是说这是最好的方法,但这是从Customer列表中为我提供了唯一的Person列表的原因。

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. 我很想听听建议或解释,这是处理它的最佳方法,还是建议的答案为什么没有产生具有唯一身份的List<Person>()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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