Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List Remove and Except behave differently

Tags:

c#

list

I am trying to subtract one C# string List from another one. I use two separate solution and both does not make sense when I look at my original list count and subtract list count amount and the result.

Result changes in each solution and both does not give the right number.

Solution 1:

  • Original list count: 2398 , tempListUnifier , this is a C# string List
  • Removal List count: 930, removalList, this is a C# string List
  • Result: 1365

    var result = tempListUnifier.Except(removalList);
    

Solution 2:

  • Original list count: 2398 , tempListUnifier , this is a C# string List
  • Removal List count: 930, removalList, this is a C# string List
  • Result: 1481

    var result = tempListUnifier;
    
    foreach(string item in removalList)
    {
        result.Remove(item);
    }
    

I wonder why do I get different result in both solution? Actually I want to get the real result, which is 2398 - 930 = 1468 . How is this possible?

like image 486
hacikho Avatar asked Jul 26 '26 07:07

hacikho


1 Answers

I wonder why do I get different result in both solution?

Most likely because tempListUnifier contains strings that are duplicated. When you call Except, all strings that are present in the "remove" list are removed, so if "cat" is found 3 times in the original list and is present in the remove list (even once), three strings will get removed.

In the second example, you most likely either have some duplicates in the removal list or some words are in the removal list that are not in the original list, or a combination of both. Since Remove only removes the first matching element, you don't have the effect from duplicate strings that you have in the Except method.

like image 177
D Stanley Avatar answered Jul 27 '26 20:07

D Stanley