3

I have two lists and I want to get the list which is the disjoint union of two lists. That is, all the items in either list that are not in both of them.

This post has almost the same query as mine, except they mean something slightly different by Disjoint Union: Disjoint Union in LINQ

what's wrong with this code snippet?

var list1 = new List<int>(){1, 2, 3}
var list2 = new List<int>(){2, 3, 4}
var intersection = list1.Intersect(list2);
list1.AddRange(list2);
list1.RemoveRange(intersection);

I'm getting type conversion issues

Community
  • 1
  • 1
Charles Taylor
  • 686
  • 6
  • 23

2 Answers2

1

Well I don't see a RemoveRange method that only takes one param, so I'm not sure what extensions you're using.

Anyways, I think this matches your definition of disjoint union:

using System.Collections.Generic;
using System.Linq;
using System;

public class Junk
{
    public static void Main()
    {
        var list1 = new List<int>(){1, 2, 3};
        var list2 = new List<int>() { 2, 3, 4 };

        var union = list1.Union(list2);
        var intersection = list1.Intersect(list2);

        foreach (var i in union.Except(intersection))
        {
            Console.WriteLine(i); //prints 1 and 4
        }
    }
}
Anssssss
  • 3,087
  • 31
  • 40
0

RemoveRange does not remove a List of objects (like AddRange adds them). It removes a specified number of objects beginning from a defined starting index.

Try this instead:

foreach (var item in intersection) { list1.Remove(item) }
Max
  • 40
  • 7