How to perform set subtraction on arrays in C#?

本秂侑毒 提交于 2019-12-10 01:11:43

问题


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" }.


回答1:


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();



回答2:


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.



来源:https://stackoverflow.com/questions/5058609/how-to-perform-set-subtraction-on-arrays-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!