【问题标题】:How to merge two objects in C# asp.net mvc3如何在 C# asp.net mvc3 中合并两个对象
【发布时间】:2012-02-14 06:20:12
【问题描述】:

我有两个这样声明的对象:

new {@class = "aClass", bar="bar"}

和

new{foo = "foo"}

如何将它们结合起来才能得到这个结果?

{@class = "aClass", bar="bar", foo = "foo"}

(以任何顺序)

我的目标是在自定义 htmlhelper 中组合额外的 html 属性。

干杯

【问题讨论】:

  • 如果它们包含重复项(意味着两个集合包含相同的属性),您期望会发生什么?
  • 还没有真正考虑过,因为我不希望它发生。但这是一个很好的观点。我想我必须重写它。

标签: c# asp.net-mvc-3


【解决方案1】:
object x = new { @class = "aClass", bar = "bar" };
object y = new { foo = "foo" };

var htmlAttributes = new RouteValueDictionary(x);
foreach (var item in new RouteValueDictionary(y))
{
    htmlAttributes[item.Key] = item.Value;
}

// at this stage htmlAttributes represent an IDictionary<string, object>
// that will contain the 3 values and which could be passed
// along to the overloaded versions of the standard helpers 
// for example:
var link = htmlHelper.ActionLink("link text", "foo", null, htmlAttributes);

// would generate:
// <a href="/home/foo" class="aClass" bar="bar" foo="foo">link text</a>

【讨论】:

  • 绝妙的答案!正是我需要的。我可以问一下,如果两个对象都包含同名的属性会发生什么?
  • @MrJD,第二个将占上风并覆盖第一个。但是,如果这不是您在 foreach 循环中想要的,您可以在覆盖之前测试 htmlAttributes 字典中是否存在键。
  • 这个功能很好。我只是不想抛出任何异常。谢谢!
  • 这对我没有用 - 但对其他地方类似问题的回答起到了作用:stackoverflow.com/questions/21188570/…
【解决方案2】:

基本上你想要的是合并 2 个匿名对象。 这个问题是关于那个主题的:

Is there an easy way to merge C# anonymous objects

【讨论】:

    【解决方案3】:

    假设这两个对象是匿名类型

    var a = new { @class = "aClass", bar = "bar" };
    var b = new { foo = "foo" };
    

    组合它们的唯一方法是创建一个包含它们两个成员的新对象:

    var result = new { a.@class, a.bar, b.foo };
    

    【讨论】:

    • 那很好,除了我没有头等舱的定义。所以我不能选择它的属性。
    猜你喜欢
    • 1970-01-01
    • 2019-10-08
    • 1970-01-01
    • 2013-04-08
    • 1970-01-01
    • 1970-01-01
    • 2012-11-30
    • 1970-01-01
    • 2011-01-01
    相关资源
    最近更新 更多