Click here to Skip to main content
15,886,578 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Fill out the C# method below to return a list of numbers that are in either list1 or list2, but not both lists.
C#
public List<int> ListDifference(List<int> list1, List<int> list2)
{
  // FILL ME OUT
}
Posted
Updated 30-Jan-13 0:51am
v2

There's a really simple way to do this with Linq. Basically, you concatenate the lists together and group them, then you search for items where the count of them is 1. Try this query out for size:
C#
List<int> countDistinct = firstList.Concat(secondList)
  .GroupBy(x => x)
  .Where(g => g.Count() == 1)
  .Select(g => g.Key).ToList();
It's as easy as that - and reads a lot easier to read than trying to compare two independent loops.

I did a comparison between this solution and the solution presented as Solution 3, and the time difference was quite staggering. I created two lists, the first had 1 million numbers in it, and the second had 2 million numbers - only 6 numbers don't match between the 2 lists. The Contains solution is a very inefficient search mechanism on large sets, so the search ends up taking an inordinate amount of time. To be honest, I gave up waiting for the second search to return after about 20 minutes. The Linq solution took 1745 milliseconds.
 
Share this answer
 
Hi,

Try this:
C#
public List<int> ListDifference(List<int> list1, List<int> list2)
{
  list1.Except(list2).Concat(list2.Except(list1)).ToList();


Enumerable.Except(TSource)[^]

Hope this helps.
 
Share this answer
 
v2
try this code to get difference

C#
for(int i=0;i<list1.Count;i++)
          {
              if(!list2.Contains(list1[i]))
                  c.Add(list1[i]);
          }

           for(int i=0;i<list2.Count;i++)
          {
              if(!list1.Contains(list2[i]) && !c.Contains(list2[i]))
                  c.Add(list1[i]);
          }
return c;
 
Share this answer
 
Comments
Pete O'Hanlon 30-Jan-13 12:31pm    
This is a very inefficient search. On large datasets, Contains takes a long time as it iterates over the items 1 by 1 looking for a match. I proposed a Linq query, below, which is much more efficient.
1. Declare and define a list that will contain your result
2. Copy those items to the result list that are in list1 but not in list2.
2.1. Use a loop that checks for each item in list1
2.2. if it is also part of list2. Copy those who aren't.
3. Copy those items to the result list that are in list2 but not in list1.
4. Return the result list.

Refer to the following links
Generic list[^], if keyword[^] List<t>.Contains(T item)[^], List<t>.Add(T item)[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900