[英]Is there an easy way to merge C# anonymous objects
Let's say I have two anonymous objects like this: 假设我有两个这样的匿名对象:
var objA = new { test = "test", blah = "blah" };
var objB = new { foo = "foo", bar = "bar" };
I want to combine them to get: 我想将它们结合起来得到:
new { test = "test", blah = "blah", foo = "foo", bar = "bar" };
I won't know what the properties are for both objA and objB at compile time. 我不知道在编译时objA和objB的属性是什么。 I want this to be like jquery's extend method. 我希望这就像jquery的extend方法。
Anybody know of a library or a .net framework class that can help me do this? 有人知道可以帮我这样做的库或.net框架类吗?
If you truly do mean dynamic in the C# 4.0 sense, then you can do something like: 如果您真的在C#4.0意义上表示动态,那么您可以执行以下操作:
static dynamic Combine(dynamic item1, dynamic item2)
{
var dictionary1 = (IDictionary<string, object>)item1;
var dictionary2 = (IDictionary<string, object>)item2;
var result = new ExpandoObject();
var d = result as IDictionary<string, object>; //work with the Expando as a Dictionary
foreach (var pair in dictionary1.Concat(dictionary2))
{
d[pair.Key] = pair.Value;
}
return result;
}
You could even write a version using reflection which takes two objects (not dynamic) and returns a dynamic. 您甚至可以使用带有两个对象(不是动态的)的反射来编写一个版本并返回一个动态。
As mentioned in comments, Luke Foust solution does not work with anonymous types. 正如评论中所提到的, Luke Foust解决方案不适用于匿名类型。 The cast to Dictionary does not work, I propose to construct the Dictionaries using the TypeDescriptor.GetProperties method: 强制转换为Dictionary不起作用,我建议使用TypeDescriptor.GetProperties方法构造字典:
public static dynamic CombineDynamics(object object1, object object2)
{
IDictionary<string, object> dictionary1 = GetKeyValueMap(object1);
IDictionary<string, object> dictionary2 = GetKeyValueMap(object2);
var result = new ExpandoObject();
var d = result as IDictionary<string, object>;
foreach (var pair in dictionary1.Concat(dictionary2))
{
d[pair.Key] = pair.Value;
}
return result;
}
private static IDictionary<string, object> GetKeyValueMap(object values)
{
if (values == null)
{
return new Dictionary<string, object>();
}
var map = values as IDictionary<string, object>;
if (map == null)
{
return map;
}
map = new Dictionary<string, object>();
foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(values))
{
map.Add(descriptor.Name, descriptor.GetValue(values));
}
return map;
}
It's now working with anonymous types: 它现在使用匿名类型:
var a = new {foo = "foo"};
var b = new {bar = "bar"};
var c = CombineDynamics(a, b);
string foobar = c.foo + c.bar;
Notes: 笔记:
My GetKeyValueMap method is based on the RouteValueDictionary class (System.Web.Routing). 我的GetKeyValueMap方法基于RouteValueDictionary类(System.Web.Routing)。 I've rewritten it (using ILSpy to disassemble it) because I think that a System.Web
class has nothing to do with object merging. 我已经重写了它(使用ILSpy来反汇编它),因为我认为System.Web
类与对象合并无关。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.