Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Comparing 2 lists

Comparing 2 lists

Scheduled Pinned Locked Moved C#
helpquestion
6 Posts 6 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • N Offline
    N Offline
    nitin_ion
    wrote on last edited by
    #1

    I want to compare 2 lists i should get result if any of their property matches I have this code

    var list1 = new List<Emp>();
    var list2 = new List<Emp>();

          list1.Add(new Emp { Empname = "nitin", ID = 1 });
    
          list2.Add(new Emp { Empname = "nitin", ID = 1 });
          list2.Add(new Emp { Empname = "nitin", ID = 1 });
          list2.Add(new Emp { Empname = "Sean", ID = 3 });
    
          foreach(var p in list1.Count()>list2.Count() ? list2:list1 )
          {
              var u=list2.Where(x => x.ID == p.ID || x.Empname == p.Empname );
          }
    

    This works fine but results are displayed twice it should be only one. currently i get {nitin,1} twice in u. where is the issue.

    P B W D 4 Replies Last reply
    0
    • N nitin_ion

      I want to compare 2 lists i should get result if any of their property matches I have this code

      var list1 = new List<Emp>();
      var list2 = new List<Emp>();

            list1.Add(new Emp { Empname = "nitin", ID = 1 });
      
            list2.Add(new Emp { Empname = "nitin", ID = 1 });
            list2.Add(new Emp { Empname = "nitin", ID = 1 });
            list2.Add(new Emp { Empname = "Sean", ID = 3 });
      
            foreach(var p in list1.Count()>list2.Count() ? list2:list1 )
            {
                var u=list2.Where(x => x.ID == p.ID || x.Empname == p.Empname );
            }
      

      This works fine but results are displayed twice it should be only one. currently i get {nitin,1} twice in u. where is the issue.

      P Offline
      P Offline
      PIEBALDconsult
      wrote on last edited by
      #2

      Don't use Linq, and break after the first match. Or maybe use distinct? Is there one?

      1 Reply Last reply
      0
      • N nitin_ion

        I want to compare 2 lists i should get result if any of their property matches I have this code

        var list1 = new List<Emp>();
        var list2 = new List<Emp>();

              list1.Add(new Emp { Empname = "nitin", ID = 1 });
        
              list2.Add(new Emp { Empname = "nitin", ID = 1 });
              list2.Add(new Emp { Empname = "nitin", ID = 1 });
              list2.Add(new Emp { Empname = "Sean", ID = 3 });
        
              foreach(var p in list1.Count()>list2.Count() ? list2:list1 )
              {
                  var u=list2.Where(x => x.ID == p.ID || x.Empname == p.Empname );
              }
        

        This works fine but results are displayed twice it should be only one. currently i get {nitin,1} twice in u. where is the issue.

        B Offline
        B Offline
        BobJanova
        wrote on last edited by
        #3

        That's what the selection on list2 will give. (Think about it for a moment.) What you want is something along the lines of

        var matches = list1.Where(x => list2.Contains(x));

        Since you apparently want a value comparison you should override Equals (and maybe == too) on Emp. That would test that all the properties matched (and I think it would make Contains work in the above expression). If you really want to check that any of the properties match, you need to write a Contains equivalent (it's a one line LINQ expression). But that seems unlikely. Ideally you'd be using the same actual object for what appears to be a reference to the same database row, but if it's actually coming out of a database provider that may not be possible. Classes that represent database entities often want value semantics for equality (unless you're using some clever entity management framework that gives you the same instance for the same row).

        1 Reply Last reply
        0
        • N nitin_ion

          I want to compare 2 lists i should get result if any of their property matches I have this code

          var list1 = new List<Emp>();
          var list2 = new List<Emp>();

                list1.Add(new Emp { Empname = "nitin", ID = 1 });
          
                list2.Add(new Emp { Empname = "nitin", ID = 1 });
                list2.Add(new Emp { Empname = "nitin", ID = 1 });
                list2.Add(new Emp { Empname = "Sean", ID = 3 });
          
                foreach(var p in list1.Count()>list2.Count() ? list2:list1 )
                {
                    var u=list2.Where(x => x.ID == p.ID || x.Empname == p.Empname );
                }
          

          This works fine but results are displayed twice it should be only one. currently i get {nitin,1} twice in u. where is the issue.

          W Offline
          W Offline
          Wayne Gaylard
          wrote on last edited by
          #4

          Just use a First query on the end of your Where query like this

          foreach(var p in list1.Count()>list2.Count() ? list2:list1 )
          {
          var u=list2.Where(x => x.ID == p.ID || x.Empname == p.Empname ).FirstOrDefault();
          }

          and that will return the first such emp. I use FirstOrDefault() in case there are no matches it will return a null Emp instead of throwing an Exception if there are no matches. You need to look out if List2 is longer than List1 as you will then be matching List2 to List2 here list2.Where. Hope this helps

          When I was a coder, we worked on algorithms. Today, we memorize APIs for countless libraries — those libraries have the algorithms - Eric Allman

          1 Reply Last reply
          0
          • N nitin_ion

            I want to compare 2 lists i should get result if any of their property matches I have this code

            var list1 = new List<Emp>();
            var list2 = new List<Emp>();

                  list1.Add(new Emp { Empname = "nitin", ID = 1 });
            
                  list2.Add(new Emp { Empname = "nitin", ID = 1 });
                  list2.Add(new Emp { Empname = "nitin", ID = 1 });
                  list2.Add(new Emp { Empname = "Sean", ID = 3 });
            
                  foreach(var p in list1.Count()>list2.Count() ? list2:list1 )
                  {
                      var u=list2.Where(x => x.ID == p.ID || x.Empname == p.Empname );
                  }
            

            This works fine but results are displayed twice it should be only one. currently i get {nitin,1} twice in u. where is the issue.

            D Offline
            D Offline
            Daniel Grondal
            wrote on last edited by
            #5

            Since you are adding Emp{Empname="nitin", ID=1} twice I guess finding it twice in your foreach shouldn't be that much of a surprise. I would use intersect. That means implementing IEquatable for your class (and perhaps GetHashCode). Like this:

            class Emp : IEquatable<Emp>
            {
            public string Empname { get; set; }
            public int ID { get; set; }

            #region IEquatable<Emp> Members

            public bool Equals(Emp other)
            {
            if (Object.ReferenceEquals(other, null)) return false;
            if (Object.ReferenceEquals(other, this)) return true;

              return ID == other.ID && 
                           Empname.Equals(other.Empname);
            

            }

            #endregion

            public override int GetHashCode()
            {
            //Calculate hash
            return Empname == null ? 0 : Empname.GetHashCode()^
            ID.GetHashCode();
            }
            }

            And then use it as:

            var u = list2.Intersect(list1);

            L 1 Reply Last reply
            0
            • D Daniel Grondal

              Since you are adding Emp{Empname="nitin", ID=1} twice I guess finding it twice in your foreach shouldn't be that much of a surprise. I would use intersect. That means implementing IEquatable for your class (and perhaps GetHashCode). Like this:

              class Emp : IEquatable<Emp>
              {
              public string Empname { get; set; }
              public int ID { get; set; }

              #region IEquatable<Emp> Members

              public bool Equals(Emp other)
              {
              if (Object.ReferenceEquals(other, null)) return false;
              if (Object.ReferenceEquals(other, this)) return true;

                return ID == other.ID && 
                             Empname.Equals(other.Empname);
              

              }

              #endregion

              public override int GetHashCode()
              {
              //Calculate hash
              return Empname == null ? 0 : Empname.GetHashCode()^
              ID.GetHashCode();
              }
              }

              And then use it as:

              var u = list2.Intersect(list1);

              L Offline
              L Offline
              Lost User
              wrote on last edited by
              #6

              Excellent Answer!

              Computers have been intelligent for a long time now. It just so happens that the program writers are about as effective as a room full of monkeys trying to crank out a copy of Hamlet.

              1 Reply Last reply
              0
              Reply
              • Reply as topic
              Log in to reply
              • Oldest to Newest
              • Newest to Oldest
              • Most Votes


              • Login

              • Don't have an account? Register

              • Login or register to search.
              • First post
                Last post
              0
              • Categories
              • Recent
              • Tags
              • Popular
              • World
              • Users
              • Groups