2

I have two objects declared like so:

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

and

new{foo = "foo"}

How do i combine them so i get this result?

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

(in any order)

My goal is to combine extra html attributes in a custom htmlhelper.

Cheers

Marijn
  • 10,367
  • 5
  • 59
  • 80
MrJD
  • 1,879
  • 1
  • 23
  • 40
  • 1
    What do you expect to happen if they contain duplicates (meaning both collections contain the same property)? – M.Babcock Feb 14 '12 at 06:25
  • Haven't really thought about it because i don't expect it to happen. But thats a very good point. I guess I'll have to override it. – MrJD Feb 14 '12 at 21:33

3 Answers3

3
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>
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Fantastic answer! Exactly what i needed. Can i just query, what will happen if both objects contain a property of the same name? – MrJD Feb 14 '12 at 22:14
  • 1
    @MrJD, the second will prevail and overwrite the first. But if this is not something that you desire inside the foreach loop you could test whether a key is present in the htmlAttributes dictionary before overwriting it. – Darin Dimitrov Feb 14 '12 at 22:18
  • That functionality is fine. I just didn't want any exceptions thrown. Thanks! – MrJD Feb 14 '12 at 22:19
  • This didn't work for me - but an answer to a similar question elsewhere did the trick: http://stackoverflow.com/questions/21188570/add-to-htmlattributes-for-custom-actionlink-helper-extension – centralscru Jun 10 '14 at 10:44
1

Basically what you want is to merge 2 anonymous objects. This question is about that subject:

Is there an easy way to merge C# anonymous objects

Community
  • 1
  • 1
HerbalMart
  • 1,669
  • 3
  • 27
  • 50
0

Assuming the two objects are of anonymous types

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

the only way to combine them is to create a new object that has the members of both of them:

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

Screenshot

dtb
  • 213,145
  • 36
  • 401
  • 431
  • That would be good, except i don't have the definition for the first class. So i can't select it's properties. – MrJD Feb 14 '12 at 21:32