Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform set subtraction on arrays in C#?

What's the simplest way to perform a set subtraction given two arrays in C#? Apparently this is dead easy in Ruby. Basically I just want to remove the elements from array a that are in array b:

string[] a = new string[] { "one", "two", "three", "four" };
string[] b = new string[] { "two", "four", "six" };
string[] c = a - b; // not valid

c should equal { "one", "three" }. b - a would yield { "six" }.

like image 293
devios1 Avatar asked Feb 20 '11 17:02

devios1


People also ask

How do you subtract elements in an array?

Find the minimum non-zero element in the array, print it and then subtract this number from all the non-zero elements of the array. If all the elements of the array are < 0, just print 0.

Can you subtract two arrays in C?

Subtract Two Arrays Create two arrays, A and B , and subtract the second, B , from the first, A . The elements of B are subtracted from the corresponding elements of A . Use the syntax -C to negate the elements of C .

Can we subtract 2 arrays C++?

If you are mentioning the subtraction of the elements that have the same indexes, you have to make sure that the array's size is equal. Then iterate through both arrays and subtract one to another using loop. The thing you want to achieve results in undefined behavior.

How do you subtract two arrays in Python?

subtract() function is used when we want to compute the difference of two array.It returns the difference of arr1 and arr2, element-wise. Parameters : arr1 : [array_like or scalar]1st Input array.


2 Answers

If you're using Linq, you can use the Except operator like this:

string [] c = a.Except(b).ToArray();

Edit: CodeInChaos makes a good point. If a contains duplicates, it will remove any duplicates as well. The alternative to make it function exactly like the Ruby version would be this:

string [] c = a.Where(x=>!b.Contains(x)).ToArray();
like image 97
Keltex Avatar answered Oct 17 '22 21:10

Keltex


public static IEnumerable<T> Minus<T>(this IEnumerable<T> enum1, IEnumerable<T> enum2)
{
    Dictionary<T, int> elements = new Dictionary<T, int>();

    foreach (var el in enum2)
    {
        int num = 0;
        elements.TryGetValue(el, out num);
        elements[el] = num + 1;
    }

    foreach (var el in enum1)
    {
        int num = 0;
        if (elements.TryGetValue(el, out num) && num > 0)
        {
            elements[el] = num - 1;
        }
        else
        {
            yield return el;
        }
    }
}

This won't remove duplicates from enum1. To be clear:

  1. { 'A', 'A' } - { 'A' } == { 'A' }
  2. { 'A', 'A' } - { 'A' } == { }

I do the first, Enumerable.Except does the second.

like image 32
xanatos Avatar answered Oct 17 '22 23:10

xanatos