NRKirby NRKirby - 3 months ago 7
C# Question

Linq Select not behaving as expected

I have a

Board
which contains a list of
OverallPartyResults
.

OverallPartyResults
has a property
PartyName
which should be distinct in the list.


I am trying to write logic for adding
OverallPartyResults
to the list Which should only add a new
OverallPartyResults
if the board doesn't contain an
OverallPartyResults
with the same code.


The linq expression I am writing is:

if (!Board.Select(i => i.PartyCode).Contains(party.PartyCode))
{
var newPartyResult = new OverallPartyResults()
{
PartyCode = party.PartyCode.Trim(),
NumberOfSeats = seatNumber

};
Board.Add(newPartyResult);
}


The expression is wrong as I am getting
OverallPartyResults
in the list with the same code - can anyone see where I am going wrong?

Answer

I suspect Trim() is the one to blame. If you have spaces in the beginning or the end of PartyCode then You will get duplicate PartyCodes

Rewrite it like this:

if (!Board.Any(i => i.PartyCode == party.PartyCode.Trim()))
{
      var newPartyResult = new OverallPartyResults()
      {
             PartyCode = party.PartyCode.Trim(),
             NumberOfSeats = seatNumber 

      };
      Board.Add(newPartyResult);
}

Use Any() instead of Select(...).Contains(). You are retreaving all PartyCodes from database (if you are using LINQ to BD). Any translates to WHERE EXISTS witch is much better (Performance wise).