删除重复项时合并键值对列表C#

时间:2018-05-23 22:22:59

标签: c# list linq dictionary

var a1 = new List<KeyValuePair<TKey, TValue>>();
var a2 = new List<KeyValuePair<TKey, TValue>>();

我有以上两个键值对列表。我想在删除重复项时将它们组合在一起。我很确定我可以通过使用LINQ来做到这一点,但我看到的示例并没有直接适用,因为它们没有指定从List<KeyValuePair<TKey, TValue>>List<KeyValuePair<TKey, TValue>>的完整过程。如果两个列表包含相同的键,它们也将具有相同的值,因此合并时保留哪个列并不重要。

4 个答案:

答案 0 :(得分:1)

你是对的,你可以在Linq做到这一点。但是,您必须要小心如何在TValue上实现相等性(当然,您必须小心TKey,但是您说这些是字符串,所以相等是明确定义的)。

void Main()
{
    var a1 = new List<KeyValuePair<string, int>>();
    var a2 = new List<KeyValuePair<string, int>>();

    a1.Add(new KeyValuePair<string, int>("A", 1));
    a1.Add(new KeyValuePair<string, int>("B", 2));
    a1.Add(new KeyValuePair<string, int>("C", 3));
    a1.Add(new KeyValuePair<string, int>("D", 4));


    a2.Add(new KeyValuePair<string, int>("B", 2));
    a2.Add(new KeyValuePair<string, int>("E", 5));
    a2.Add(new KeyValuePair<string, int>("C", 33));

    var distinct = a1.Union(a2).Distinct();

    foreach(var kv in distinct)
    {
        Console.WriteLine($"{kv.Key}={kv.Value}");
    }
}

这将打印以下结果:

A=1
B=2
C=3
D=4
E=5
C=33

答案 1 :(得分:1)

如果(如上所述)你不介意选择哪一个重复,那么:

var result = a1.Concat(a2)
               .GroupBy(x => x.Key)
               .Select(g => g.First())
               .ToList();

或者,如果您有很多项目,更好的方法是使用(更高效)DistinctBy实施。这个(或多或少)来自MoreLinq

public static class LinqEx
{
    public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source,
        Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer = null)
    {
        if (source == null) throw new ArgumentNullException(nameof(source));
        if (keySelector == null) throw new ArgumentNullException(nameof(keySelector));

        return _(); IEnumerable<TSource> _()
        {
            var knownKeys = new HashSet<TKey>(comparer);
            foreach (var element in source)
            {
                if (knownKeys.Add(keySelector(element)))
                    yield return element;
            }
        }

    }
}

然后

var result = a1.Concat(a2)
               .DistinctBy(x => x.Key)
               .ToList();

答案 2 :(得分:0)

假设&#34;两个列表包含相同的键,它们也将具有相同的值&#34;你可以这样做:

var a3 = new List<KeyValuePair<TKey, TValue>>();
a3.AddRange(a1);
a3.AddRange(a2);
var a3 = a3.Distinct().ToList();

或:

var a3 = a1.Union(a2).ToList();

答案 3 :(得分:0)

如果您创建一个字典并迭代两个列表并将它们添加到字典中,该怎么办?字典不能有相同的密钥,因此在尝试添加时请使用try catch。

Dictionary<TKey,TValue> myDictionary = new Dictionary();

//Iterate over list
//add try catch to attempt to add key and value to the dictionary.
相关问题