使用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>()?
2 回答

智慧大石
TA貢獻1946條經驗 獲得超3個贊
這是有效的代碼。
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
TA貢獻1834條經驗 獲得超8個贊
一種方法是使用GroupBy
:
var uniquePersons = customers .GroupBy(c => new Person() {Id = c.Id, Name = c.Name}) .Select(g => g.Key) .ToList();
- 2 回答
- 0 關注
- 176 瀏覽
添加回答
舉報
0/150
提交
取消