我在 LINQ 中使用 distinct
时遇到问题。我有这个列表:
LineIdChanged LineId OldGatewayPCId NewGatewayPCId LineStringID PlantID
1 93 83 88 160 2
2 93 83 88 161 2
3 94 82 87 162 2
4 94 82 87 163 2
我尝试的是获得一个不同的 LineId 值,因此在这种情况下我应该只获得两个对象而不是所有四个对象。我试过这个:
var s = (from n in _dataBaseProvider.SelectPjdGatewayLineChanged(selectedSourcePlant.LPS_Database_ID)
select new PjdGatewayLineChanged() { LineId = n.LineId, LpsLineNo = n.LpsLineNo, LineIdChanged = n.LineIdChanged}).Distinct();
LinesOld = s.ToList();
但这给了我所有 4 个对象。
最佳答案
您需要使用 MoreLINQ's DistinctBy
:
var s =
(from n in _dataBaseProvider.SelectPjdGatewayLineChanged
(selectedSourcePlant.LPS_Database_ID)
select new PjdGatewayLineChanged
{
LineId = n.LineId,
LpsLineNo = n.LpsLineNo,
LineIdChanged = n.LineIdChanged
})
.DistinctBy(p => p.LineId);
关于c# - 在 C# 中使用 LINQ Distinct,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18057310/