你如何在.NET中克隆字典?

时间:2010-02-17 09:50:59

标签: .net data-structures

我知道我们应该使用字典而不是哈希表。我找不到克隆字典的方法。即使将它转换为ICollection我也是为了获得SyncRoot,我知道这也是不赞成的。

我正在忙着改变它。我是否正确地假设没有办法以通用的方式实现任何类型的克隆,这就是字典不支持克隆的原因?

5 个答案:

答案 0 :(得分:57)

使用带有Dictionary的构造函数。见这个例子

var dict = new Dictionary<string, string>();

dict.Add("SO", "StackOverflow");

var secondDict = new Dictionary<string, string>(dict);

dict = null;

Console.WriteLine(secondDict["SO"]);

只是为了好玩..你可以使用LINQ!这是一种更通用的方法。

var secondDict = (from x in dict
                  select x).ToDictionary(x => x.Key, x => x.Value);

修改

这应该适用于参考类型,我尝试了以下内容:

internal class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public User Parent { get; set; }
}

以及上面的修改代码

var dict = new Dictionary<string, User>();

dict.Add("First", new User 
    { Id = 1, Name = "Filip Ekberg", Parent = null });

dict.Add("Second", new User 
    { Id = 2, Name = "Test test", Parent = dict["First"] });

var secondDict = (from x in dict
                  select x).ToDictionary(x => x.Key, x => x.Value);

dict.Clear();

dict = null;

Console.WriteLine(secondDict["First"].Name);

哪个输出“Filip Ekberg”。

答案 1 :(得分:2)

这是我曾经写过的一种快速而又脏的克隆方法......我认为最初的想法来自CodeProject。

Imports System.Runtime.Serialization
Imports System.Runtime.Serialization.Formatters.Binary

Public Shared Function Clone(Of T)(ByVal inputObj As T) As T
    'creating a Memorystream which works like a temporary storeage '
    Using memStrm As New MemoryStream()
        'Binary Formatter for serializing the object into memory stream '
        Dim binFormatter As New BinaryFormatter(Nothing, New StreamingContext(StreamingContextStates.Clone))

        'talks for itself '
        binFormatter.Serialize(memStrm, inputObj)

        'setting the memorystream to the start of it '
        memStrm.Seek(0, SeekOrigin.Begin)

        'try to cast the serialized item into our Item '
        Try
            return DirectCast(binFormatter.Deserialize(memStrm), T)
        Catch ex As Exception
            Trace.TraceError(ex.Message)
            return Nothing
        End Try
    End Using
End Function

用途:

Dim clonedDict As Dictionary(Of String, String) = Clone(Of Dictionary(Of String, String))(yourOriginalDict)

答案 2 :(得分:0)

因为任何人都需要vb.net版本

Dim dictionaryCloned As Dictionary(Of String, String)
dictionaryCloned  = (From x In originalDictionary Select x).ToDictionary(Function(p) p.Key, Function(p) p.Value)

答案 3 :(得分:0)

对于原始类型字典

Public Sub runIntDictionary()
  Dim myIntegerDict As New Dictionary(Of Integer, Integer) From {{0, 0}, {1, 1}, {2, 2}}
  Dim cloneIntegerDict As New Dictionary(Of Integer, Integer)
  cloneIntegerDict = myIntegerDict.Select(Function(x) x.Key).ToList().ToDictionary(Of Integer, Integer)(Function(x) x, Function(y) myIntegerDict(y))
End Sub

对于实现ICloneable的对象的字典

Public Sub runObjectDictionary()
  Dim myDict As New Dictionary(Of Integer, number) From {{3, New number(3)}, {4, New number(4)}, {5, New number(5)}}
  Dim cloneDict As New Dictionary(Of Integer, number)
  cloneDict = myDict.Select(Function(x) x.Key).ToList().ToDictionary(Of Integer, number)(Function(x) x, Function(y) myDict(y).Clone)
End Sub

Public Class number
  Implements ICloneable
  Sub New()
  End Sub
  Sub New(ByVal newNumber As Integer)
    nr = newnumber
  End Sub
  Public nr As Integer

  Public Function Clone() As Object Implements ICloneable.Clone
    Return New number With {.nr = nr}
  End Function
  Public Overrides Function ToString() As String
    Return nr.ToString
  End Function
End Class

答案 4 :(得分:0)

对于简单的 Dictionary

public static Dictionary<string, object> DictionaryClone(Dictionary<string, object> _Datas)
{
    Dictionary<string, object> output = new Dictionary<string, object>();

    if (_Datas != null)
    {
        foreach (var item in _Datas)
            output.Add(item.Key, item.Value);
    }

    return output;
}