Question

I am trying to create a string list that contains all of the items that are different between List A and List B. I have the following code, and I feel that I am close, but I am getting syntax errors on the last line. Any help would be appreciated:

 List<string> ListA = new List<string>(textBox_CompareListA.Text.Split(delimiterChars, StringSplitOptions.RemoveEmptyEntries));
 List<string> ListB = new List<string>(textBox_CompareListB.Text.Split(delimiterChars, StringSplitOptions.RemoveEmptyEntries));

 List<string> DifferencesList = ListA.Except(ListB, StringComparer.OrdinalIgnoreCase).Union(ListB.Except(ListA, StringComparer.OrdinalIgnoreCase));

Here is the error: http://screencast.com/t/Y8S9LC2Y

Syntax Error

Was it helpful?

Solution

You should try calling Enumerable.ToList to get the List from your query expression.

List<string> DifferencesList = ListA.Except(ListB, StringComparer.OrdinalIgnoreCase).Union(ListB.Except(ListA, StringComparer.OrdinalIgnoreCase)).ToList();

OTHER TIPS

I can't resist pointing out this:

 List<string> diffs = ListA.Union(ListB).Except(ListA.Intersect(ListB)).ToList();

Depending on your data it could be faster (I believe if the Intersection is small).

Change the last line code from :

List<string> DifferencesList = ListA.Except(ListB, StringComparer.OrdinalIgnoreCase).Union(ListB.Except(ListA, StringComparer.OrdinalIgnoreCase));

To :

var DifferencesList = ListA.Except(ListB, StringComparer.OrdinalIgnoreCase).Union(ListB.Except(ListA, StringComparer.OrdinalIgnoreCase));

Or :

IEnumerable<string> DifferencesList = ListA.Except(ListB, StringComparer.OrdinalIgnoreCase).Union(ListB.Except(ListA, StringComparer.OrdinalIgnoreCase));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top