Thursday, February 9, 2012

Linq Except with Duplicate Members

List<string> popcapGames = new List<string> { "Zuma",

"Chuzzled",

"Bejeweled",

"Plants vs Zombies",

"Zuma",

"Peggle"

};

// I want all the elements except Chuzzled.

List<string> excludingChuzzled = popcapGames.Except(popcapGames.Where(x => x == "Chuzzled")).ToList();

// I expect excludingChuzzled to be: { "Zuma",

// "Bejeweled",

// "Plants vs Zombies",

// "Zuma",

// "Peggle"

// };

//

//

//

//

//

// but actually its: { "Zuma",

// "Bejeweled",

// "Plants vs Zombies",

// "Peggle"

// };

// What happened to my duplicate "Zuma"?

//

// I don't like Except any more.

3 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. So you really do want to keep one duplicate but remove another?
    You can probably imagine that Except adds the lists together in RAM then performs a distinct.

    using System;
    using System.Collections.Generic;
    using System.Linq;

    namespace Coderoo1
    {
    class Program
    {
    static void Main(string[] args)
    {
    List popcapGames = new List {
    "Zuma",
    "Chuzzled",
    "Bejeweled",
    "Plants vs Zombies",
    "Zuma",
    "Peggle"
    }.Except(new List{"Chuzzled"}).ToList();

    popcapGames
    .ForEach(s => Console.WriteLine(s));
    }
    }
    }
    // I will see how I can change this to keep both copies of Zuma

    ReplyDelete
  3. This will work, but it does not use Except:
    using System;
    using System.Collections.Generic;
    using System.Linq;

    namespace Coderoo1
    {
    class Program
    {
    static void Main(string[] args)
    {
    List popcapGames = new List {
    "Zuma",
    "Chuzzled",
    "Bejeweled",
    "Plants vs Zombies",
    "Zuma",
    "Peggle"
    };

    popcapGames.Where(s => !s.Equals("Chuzzled")).ToList()
    .ForEach(s => Console.WriteLine(s));
    }
    }
    }

    ReplyDelete