Подтвердить что ты не робот

Как клонировать словарь в .NET?

Я знаю, что лучше использовать словари, а не хеш-таблицы. Однако я не могу найти способ клонировать словарь. Даже если вы отправляете его в ICollection, который я делаю, чтобы получить SyncRoot, который, как я знаю, также не одобряется.

Я сейчас занят этим. Я полагаюсь на правильное предположение, что нет способа реализовать какой-либо клонирование в общем виде, поэтому клон не поддерживается для словаря?

4b9b3361

Ответ 1

Используйте конструктор, который использует словарь. См. Этот пример

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);

Edit

Это должно хорошо работать со ссылочными типами, я попробовал следующее:

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);

Какие выходы "Филип Экберг".

Ответ 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

Useage:

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

Ответ 3

Просто потому, что кому-то нужна версия 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)