Combining lists but getting unique members

Posted by MC on Stack Overflow See other posts from Stack Overflow or by MC
Published on 2010-04-09T01:29:08Z Indexed on 2010/04/09 1:33 UTC
Read the original article Hit count: 399

Filed under:
|

I have a bit of a special requirement when combining lists. I will try to illustrate with an example. Lets say I'm working with 2 lists of GamePlayer objects. GamePlayer has a property called LastGamePlayed. A unique GamePlayer is identified through the GamePlayer.ID property. Now I'd like to combine listA and listB into one list, and if a given player is present in both lists I'd like to keep the value from listA.

I can't just combine the lists and use a comparer because my uniqueness is based on ID, and if my comparer checks ID I will not have control over whether it picks the element of listA or listB. I need something like:

for each player in listB
{
    if not listA.Contains(player) 
    {
        listFinal.Add(player)
    }
}

However, is there a more optimal way to do this instead of searching listA for each element in listB?

© Stack Overflow or respective owner

Related posts about .NET

Related posts about lists