12,767,637 members (52,083 online)
Rate this:
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.
```public List<int> ListDifference(List<int> list1, List<int> list2)
{
// FILL ME OUT
}```
Posted 29-Jan-13 23:58pm
rummer1K
Updated 30-Jan-13 1:51am
v2

Rate this:

## Solution 4

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:
```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.
Rate this:

## Solution 5

Hi,

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

Enumerable.Except(TSource)[^]

Hope this helps.
v2
Rate this:

## Solution 3

try this code to get difference

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

for(int i=0;i<list2.Count;i++)
{
if(!list1.Contains(list2[i]) && !c.Contains(list2[i]))
}
return c;
```
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.
Rate this:

## Solution 2

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.

Generic list[^], if keyword[^] List<t>.Contains(T item)[^], List<t>.Add(T item)[^]

Top Experts
Last 24hrsThis month
 Graeme_Grant 300 Karthik Bangalore 205 Jochen Arndt 150 ppolymorphe 125 Peter Leow 95
 Graeme_Grant 206 Karthik Bangalore 180 Jochen Arndt 110 Peter Leow 75 OriginalGriff 58