Using LINQ Distinct in C#

c#, linq

Solution

You need to use 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);

Problem

I have an issue using `distinct` in LINQ. I have this list: ``` 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 ``` What I have tried is to get a distinct LineId value, so in this case I should only get two objects instead of all four objects. I have tried this: ``` 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(); ``` But this gives me all 4 objects.

Original source

Related problems