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

使用LINQ,我尝试选择唯一的Customer作为Person对象。JSON我在下面的示例中使用数据,但我正在POCO使用C#. 在这个例子中,我选择JSON让事情变得简单。


我有以下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

  }

]

我想将独特的客户作为Person对象,结果应该如下所示:


[

  {

     "id": 123,

     "name": "John Smith"

  },

  {

     "id": 234,

     "name": "Jane Doe"

  }

]

下面应该给我唯一的 ID。


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

我现在如何Person从中提取唯一的List<Customer>()?


不负相思意
浏览 89回答 2
2回答

智慧大石

这是有效的代码。var uniquePersons = customers                         .Select(x => new Person() { Id = x.Id, Name = x.Name })                         .GroupBy(g => g.Id)                         .Select(x => x.First())                         .ToList();我并不是说这是最好的方法,但这就是给我一个独特的列表的Person原因Customer。我很想听到建议或解释,这是否是处理该问题的最佳方法,或者为什么建议的答案没有产生List<Person>()独特的人。

MMMHUHU

一种方法是使用GroupBy:var&nbsp;uniquePersons&nbsp;=&nbsp;customers &nbsp;&nbsp;&nbsp;&nbsp;.GroupBy(c&nbsp;=>&nbsp;new&nbsp;Person()&nbsp;{Id&nbsp;=&nbsp;c.Id,&nbsp;Name&nbsp;=&nbsp;c.Name}) &nbsp;&nbsp;&nbsp;&nbsp;.Select(g&nbsp;=>&nbsp;g.Key) &nbsp;&nbsp;&nbsp;&nbsp;.ToList();
打开App,查看更多内容
随时随地看视频慕课网APP