c#中关联变量的名称

本文关键字:变量 关联 | 更新日期: 2023-09-27 18:15:56

你怎么称呼这个方法,(它在。net中可用吗?)

var list1 = new List<int>() { 1, 2, 2, 3, 4 };
var list2 = new List<int>() { 1, 2, 3};
var results = list1.diff(list2);
results:
{ 2, 4 }

c#中关联变量的名称

最接近的是Except LINQ运算符

产生两个序列的集合差。

虽然在你的例子中,它将导致:

{ 4 }

我不相信你想要的东西有直接的类似物

您实际上需要一个多集实现。虽然在BCL中没有现成的多集,但这里和链接问题中有一些想法。

或者你可以自己实现一个,这并不复杂:

class Multiset<K> // maybe implement IEnumerable?
{
    Dictionary<K, int> arities = new Dictionary<K, int>();
    ...
    Multiset<K> Except(Multiset<K> other)
    {
        foreach (var k in arities.keys)
        {
            int arity = arities[k];
            if (other.Contains(k))
                arity -= other.Arity(k);
            if (arity > 0)
                result.Add(k, arity);
        }
        return result;
    }
}

这将返回您想要的结果,您可以在扩展方法中重构它:

var results = list1.GroupBy(p => p).Select(p => new { item = p.Key, count = p.Count() })
                .Concat(list2.GroupBy(p => p).Select(p => new { item = p.Key, count = -p.Count() }))
                .GroupBy(p => p.item).Select(p => new { item = p.Key, count = p.Sum(q => q.count) })
                .Where(p => p.count > 0)
                .SelectMany(p => Enumerable.Repeat(p.item, p.count));

像这样:(参见oded的帖子链接到msdn)

int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 }; 
int[] numbersB = { 1, 3, 5, 7, 8 }; 
IEnumerable<int> aOnlyNumbers = numbersA.Except(numbersB);