Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 158629
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 11, 20262026-05-11T10:42:55+00:00 2026-05-11T10:42:55+00:00

Here is an interesting issue I noticed when using the Except Operator: I have

  • 0

Here is an interesting issue I noticed when using the Except Operator: I have list of users from which I want to exclude some users:

The list of users is coming from an XML file:

The code goes like this:

interface IUser {      int ID { get; set; }      string Name { get; set; } }  class User: IUser {      #region IUser Members      public int ID     {         get;         set;     }      public string Name     {         get;         set;     }      #endregion      public override string ToString()     {         return ID + ':' +Name;     }       public static IEnumerable<IUser> GetMatchingUsers(IEnumerable<IUser> users)     {          IEnumerable<IUser> localList = new List<User>          {             new User{ ID=4, Name='James'},             new User{ ID=5, Name='Tom'}           }.OfType<IUser>();          var matches = from u in users                        join lu in localList                            on u.ID equals lu.ID                        select u;          return matches;     } }  class Program {     static void Main(string[] args)     {         XDocument doc = XDocument.Load('Users.xml');         IEnumerable<IUser> users = doc.Element('Users').Elements('User').Select             (u => new User                 { ID = (int)u.Attribute('id'),                   Name = (string)u.Attribute('name')                 }             ).OfType<IUser>();       //still a query, objects have not been materialized           var matches = User.GetMatchingUsers(users);         var excludes = users.Except(matches);    // excludes should contain 6 users but here it contains 8 users      } } 

When I call User.GetMatchingUsers(users) I get 2 matches as expected. The issue is that when I call users.Except(matches) The matching users are not being excluded at all! I am expecting 6 users ut ‘excludes’ contains all 8 users instead.

Since all I’m doing in GetMatchingUsers(IEnumerable<IUser> users) is taking the IEnumerable<IUser> and just returning the IUsers whose ID’s match( 2 IUsers in this case), my understanding is that by default Except will use reference equality for comparing the objects to be excluded. Is this not how Except behaves?

What is even more interesting is that if I materialize the objects using .ToList() and then get the matching users, and call Except, everything works as expected!

Like so:

IEnumerable<IUser> users = doc.Element('Users').Elements('User').Select             (u => new User                 { ID = (int)u.Attribute('id'),                   Name = (string)u.Attribute('name')                 }             ).OfType<IUser>().ToList();   //explicity materializing all objects by calling ToList()  var matches = User.GetMatchingUsers(users); var excludes = users.Except(matches);   // excludes now contains 6 users as expected 

I don’t see why I should need to materialize objects for calling Except given that its defined on IEnumerable<T>?

Any suggesstions / insights would be much appreciated.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. 2026-05-11T10:42:56+00:00Added an answer on May 11, 2026 at 10:42 am

    I think I know why this fails to work as expected. Because the initial user list is a LINQ expression, it is re-evaluated each time it is iterated (once when used in GetMatchingUsers and again when doing the Except operation) and so, new user objects are created. This would lead to different references and so no matches. Using ToList fixes this because it iterates the LINQ query once only and so the references are fixed.

    I’ve been able to reproduce the problem you have and having investigated the code, this seems like a very plausible explanation. I haven’t proved it yet, though.

    Update
    I just ran the test but outputting the users collection before the call to GetMatchingUsers, in that call, and after it. Each time the hash code for the object was output and they do indeed have different values each time indicating new objects, as I suspected.

    Here is the output for each of the calls:

    ==> Start ID=1, Name=Jeff, HashCode=39086322 ID=2, Name=Alastair, HashCode=36181605 ID=3, Name=Anthony, HashCode=28068188 ID=4, Name=James, HashCode=33163964 ID=5, Name=Tom, HashCode=14421545 ID=6, Name=David, HashCode=35567111 <== End ==> Start ID=1, Name=Jeff, HashCode=65066874 ID=2, Name=Alastair, HashCode=34160229 ID=3, Name=Anthony, HashCode=63238509 ID=4, Name=James, HashCode=11679222 ID=5, Name=Tom, HashCode=35410979 ID=6, Name=David, HashCode=57416410 <== End ==> Start ID=1, Name=Jeff, HashCode=61940669 ID=2, Name=Alastair, HashCode=15193904 ID=3, Name=Anthony, HashCode=6303833 ID=4, Name=James, HashCode=40452378 ID=5, Name=Tom, HashCode=36009496 ID=6, Name=David, HashCode=19634871 <== End 

    And, here is the modified code to show the problem:

    using System.Xml.Linq; using System.Collections.Generic; using System.Linq; using System;  interface IUser {     int ID     {         get;         set;     }     string Name     {         get;         set;     } }  class User : IUser {      #region IUser Members      public int ID     {         get;         set;     }      public string Name     {         get;         set;     }      #endregion      public override string ToString()     {         return ID + ':' + Name;     }       public static IEnumerable<IUser> GetMatchingUsers(IEnumerable<IUser> users)     {         IEnumerable<IUser> localList = new List<User>          {             new User{ ID=4, Name='James'},             new User{ ID=5, Name='Tom'}           }.OfType<IUser>();          OutputUsers(users);         var matches = from u in users                       join lu in localList                           on u.ID equals lu.ID                       select u;         return matches;     }      public static void OutputUsers(IEnumerable<IUser> users)     {         Console.WriteLine('==> Start');         foreach (IUser user in users)         {             Console.WriteLine('ID=' + user.ID.ToString() + ', Name=' + user.Name + ', HashCode=' + user.GetHashCode().ToString());         }         Console.WriteLine('<== End');     } }  class Program {     static void Main(string[] args)     {         XDocument doc = new XDocument(             new XElement(                 'Users',                 new XElement('User', new XAttribute('id', '1'), new XAttribute('name', 'Jeff')),                 new XElement('User', new XAttribute('id', '2'), new XAttribute('name', 'Alastair')),                 new XElement('User', new XAttribute('id', '3'), new XAttribute('name', 'Anthony')),                 new XElement('User', new XAttribute('id', '4'), new XAttribute('name', 'James')),                 new XElement('User', new XAttribute('id', '5'), new XAttribute('name', 'Tom')),                 new XElement('User', new XAttribute('id', '6'), new XAttribute('name', 'David'))));         IEnumerable<IUser> users = doc.Element('Users').Elements('User').Select             (u => new User             {                 ID = (int)u.Attribute('id'),                 Name = (string)u.Attribute('name')             }             ).OfType<IUser>();       //still a query, objects have not been materialized           User.OutputUsers(users);         var matches = User.GetMatchingUsers(users);         User.OutputUsers(users);         var excludes = users.Except(matches);    // excludes should contain 6 users but here it contains 8 users      } } 
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 86k
  • Answers 87k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer I was trying to connect to the database using the… May 11, 2026 at 5:27 pm
  • Editorial Team
    Editorial Team added an answer I'm not sure that changing the url is possible through… May 11, 2026 at 5:27 pm
  • Editorial Team
    Editorial Team added an answer It sounds as if you're building an interface that performs… May 11, 2026 at 5:27 pm

Related Questions

I'm experiencing what I believe is a circular dependency issue with my PHP application.
This originally was a problem I ran into at work, but is now something
I ran into an interesting (and very frustrating) issue with the equals() method today
Ok I've got a bit of an interesting problem on my hands. Here's a

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.