Skip to content
This repository has been archived by the owner on Dec 24, 2022. It is now read-only.

Commit

Permalink
Add MergeIntoObjectDictionary with test
Browse files Browse the repository at this point in the history
  • Loading branch information
mythz committed Apr 22, 2018
1 parent 3ec23a3 commit 573518c
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
14 changes: 12 additions & 2 deletions src/ServiceStack.Text/PlatformExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -660,8 +660,7 @@ public static Dictionary<string, object> ToObjectDictionary(this object obj)

var type = obj.GetType();

ObjectDictionaryDefinition def;
if (!toObjectMapCache.TryGetValue(type, out def))
if (!toObjectMapCache.TryGetValue(type, out var def))
toObjectMapCache[type] = def = CreateObjectDictionaryDefinition(type);

var dict = new Dictionary<string, object>();
Expand Down Expand Up @@ -776,5 +775,16 @@ public static Dictionary<string, object> ToSafePartialObjectDictionary<T>(this T
}
return to;
}

public static Dictionary<string, object> MergeIntoObjectDictionary(this object obj, params object[] sources)
{
var to = obj.ToObjectDictionary();
foreach (var source in sources)
foreach (var entry in source.ToObjectDictionary())
{
to[entry.Key] = entry.Value;
}
return to;
}
}
}
25 changes: 25 additions & 0 deletions tests/ServiceStack.Text.Tests/AutoMappingObjectDictionaryTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -127,5 +127,30 @@ public void Can_convert_from_ObjectDictionary_into_AutoQuery_DTO()
Assert.That(request.Meta, Is.EquivalentTo(new Dictionary<string, object> {{"foo", "bar"}}));
}

public class Employee
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string DisplayName { get; set; }
}

[Test]
public void Can_create_new_object_from_merged_objects()
{
var customer = new User { FirstName = "John", LastName = "Doe" };
var map = customer.MergeIntoObjectDictionary(new {Initial = "Z"});
map["DisplayName"] = map["FirstName"] + " " + map["Initial"] + " " + map["LastName"];
var employee = map.FromObjectDictionary<Employee>();

Dictionary<string,object> MergeObjects(params object[] sources) {
var to = new Dictionary<string, object>();
sources.Each(x => x.ToObjectDictionary().Each(entry => to[entry.Key] = entry.Value));
return to;
}

Assert.That(employee.DisplayName, Is.EqualTo("John Z Doe"));
}

}

}

0 comments on commit 573518c

Please sign in to comment.