Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disjoint Union in C# Lists

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

like image 668
Charles Taylor Avatar asked Oct 14 '25 16:10

Charles Taylor


1 Answers

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
        }
    }
}
like image 119
Anssssss Avatar answered Oct 17 '25 06:10

Anssssss