How to perform set subtraction on arrays in C#?

前端 未结 2 507
名媛妹妹
名媛妹妹 2021-01-04 03:09

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 <

相关标签:
2条回答
  • 2021-01-04 03:40

    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();
    
    0 讨论(0)
  • 2021-01-04 03:56
    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.

    0 讨论(0)
提交回复
热议问题