C# Merging 2 dictionaries

后端 未结 4 1452
半阙折子戏
半阙折子戏 2020-12-31 00:04

I\'m developing an app in C# targeting .NET 3.5. In it, I have 2 similar dictionaries that contain validation criteria for a specific set of elements in my app. Both dicti

4条回答
  •  离开以前
    2020-12-31 00:57

    I think the answer I selected originally is still the best answer for this particular case, I found myself in another similar situation a little while ago where I had 2 IEnumerable<> objects that I wanted to convert to a dictionary and merge together in a similar fashion so I thought I would add that solution here to help someone in the future. Rather than converting both to a dictionary and using the method in the selected answer, I found a new approach.

    I actually posted the initial solution on SE-CodeReview and actually had a suggestion to refine it further. Here's the final code I used:

    public Dictionary Merge(XElement element1, XElement element2)
    {
        IEnumerable firstFoos = GetXmlData(element1); // parse 1st set from XML
        IEnumerable secondFoos = GetXmlData(element2); // parse 2nd set from XML
    
        var result = firstFoos.Union(secondFoos).ToDictionary(k=>k.Name, v=>v);
    
        return result;
    }
    
    public class Foo
    {
        public String Name { get; }
    
        // other Properties and Methods
        // .
        // .
        // .
    
        public override Boolean Equals(Object obj)
        {
            if (obj is Foo)
            {
                return this.Name == ((Foo)obj).Name;            
            }
    
            return false;
        }
    }
    

    The key to this is Foo must override Equals() to define what Foo objects can be considered duplicate, and the members that define which objects are duplicate should also be the Dictionary<> key (in this case Name)

    If you can't override Equals() in Foo, then the other option is to use Concat() and GroupBy() instead of Union()

    public Dictionary Merge(XElement element1, XElement element2)
    {
        IEnumerable firstFoos = GetXmlData(element1); // parse 1st set from XML
        IEnumerable secondFoos = GetXmlData(element2); // parse 2nd set from XML
    
        var result = firstFoos.Concat(secondFoos)
                              .GroupBy(foo => foo.Name)
                              .Select(grp => grp.First())
                              .ToDictionary(k=>k.Name, v=>v);
    
        return result;
    }
    

提交回复
热议问题