合并匿名类型 [英] Merging anonymous types
本文介绍了合并匿名类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何合并两个匿名类型,这样的结果包含源对象的属性?
无功源1 =新
{
富=富,
巴=栏
}无功源2 =新
{
巴兹=巴兹
}VAR合并=合并(来源1,源2)//< - 这里的地方魔术应该发生//合并:
// {
//富=foo的,
//栏=酒吧,
//巴兹=巴兹
//}
编辑:
这是我想出了最后(通过@ BlueMonkMN的回答启发):
公共动态合并(item1的对象,对象ITEM2)
{
如果(ITEM1 == NULL || ITEM2 == NULL)
返回ITEM1? ITEM2 ??新ExpandoObject(); 动态的expando =新ExpandoObject();
VAR的结果=的expando作为IDictionary的<字符串对象&gt ;;
的foreach(System.Reflection.PropertyInfo网络item1.GetType()的GetProperties())
{
结果[fi.Name] = fi.GetValue(项目1,NULL);
}
的foreach(System.Reflection.PropertyInfo网络item2.GetType()的GetProperties())
{
结果[fi.Name] = fi.GetValue(项目2,NULL);
}
返回结果;
}
解决方案
因此,这里是什么我终于想出了(由@ BlueMonkMN的回答启发):
公共动态合并(item1的对象,对象ITEM2)
{
如果(ITEM1 == NULL || ITEM2 == NULL)
返回ITEM1? ITEM2 ??新ExpandoObject(); 动态的expando =新ExpandoObject();
VAR的结果=的expando作为IDictionary的<字符串对象&gt ;;
的foreach(System.Reflection.PropertyInfo网络item1.GetType()的GetProperties())
{
结果[fi.Name] = fi.GetValue(项目1,NULL);
}
的foreach(System.Reflection.PropertyInfo网络item2.GetType()的GetProperties())
{
结果[fi.Name] = fi.GetValue(项目2,NULL);
}
返回结果;
}
How can I merge two anonymous types, so that the result contains the properties of both source objects?
var source1 = new
{
foo = "foo",
bar = "bar"
}
var source2 = new
{
baz = "baz"
}
var merged = Merge(source1, source2) // <-- here's where the magic should happen
// merged:
// {
// foo = "foo",
// bar = "bar",
// baz = "baz"
// }
EDIT:
This is what I came up with finally (inspired by @BlueMonkMN's answer):
public dynamic Merge(object item1, object item2)
{
if (item1 == null || item2 == null)
return item1 ?? item2 ?? new ExpandoObject();
dynamic expando = new ExpandoObject();
var result = expando as IDictionary<string, object>;
foreach (System.Reflection.PropertyInfo fi in item1.GetType().GetProperties())
{
result[fi.Name] = fi.GetValue(item1, null);
}
foreach (System.Reflection.PropertyInfo fi in item2.GetType().GetProperties())
{
result[fi.Name] = fi.GetValue(item2, null);
}
return result;
}
解决方案
So here's, what I finally came up with (inspired by @BlueMonkMN's answer):
public dynamic Merge(object item1, object item2)
{
if (item1 == null || item2 == null)
return item1 ?? item2 ?? new ExpandoObject();
dynamic expando = new ExpandoObject();
var result = expando as IDictionary<string, object>;
foreach (System.Reflection.PropertyInfo fi in item1.GetType().GetProperties())
{
result[fi.Name] = fi.GetValue(item1, null);
}
foreach (System.Reflection.PropertyInfo fi in item2.GetType().GetProperties())
{
result[fi.Name] = fi.GetValue(item2, null);
}
return result;
}
这篇关于合并匿名类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文