Convert Dictionary<String, Object> to Anonymous Object

Convert Dictionarystring, object To Anonymous Object?

If you really want to convert the dictionary to an object that has the items of the dictionary as properties, you can use ExpandoObject:

var dict = new Dictionary<string, object> { { "Property", "foo" } };
var eo = new ExpandoObject();
var eoColl = (ICollection<KeyValuePair<string, object>>)eo;

foreach (var kvp in dict)
{
eoColl.Add(kvp);
}

dynamic eoDynamic = eo;

string value = eoDynamic.Property;

Convert dictionary to anonymous object

If you don't know the exact members of the dictionary you can use dynamic to get a pretty syntax as shown below. However, if you know the members of the dictionary and the types, then you could create your own class and do the conversion yourself. There might exists a framework to do that automatically.

using System;
using System.Collections.Generic;
using System.Text;
using System.Dynamic;

namespace DynamicTest
{
public class DynamicDictionary : DynamicObject
{
Dictionary<string, object> dict;

public DynamicDictionary(Dictionary<string, object> dict)
{
this.dict = dict;
}

public override bool TrySetMember(SetMemberBinder binder, object value)
{
dict[binder.Name] = value;
return true;
}

public override bool TryGetMember(GetMemberBinder binder, out object result)
{
return dict.TryGetValue(binder.Name, out result);
}
}

class Program
{
static void Main(string[] args)
{
dynamic foo = new DynamicDictionary(new Dictionary<string, object> { { "test1", 1 } });

foo.test2 = 2;

Console.WriteLine(foo.test1); // Prints 1
Console.WriteLine(foo.test2); // Prints 2
}
}
}

Convert Dictionary to anonymous object in c#?

You don't need an anonymous object. Looking at the SqlKata docs, you can just build up the query by looping over the dictionary, something like this:

//Assuming the dictionary is something like Dictionary<string, object>

var query = new Query("Posts");

foreach(var element in dictionary)
{
query = query.Where(element.Key, element.Value);
}

var result = query.Get();

Note: Never even heard of SqlKata before so this is just from looking at the docs.

Converting an anonymous type to a dictionary

exception is here :

 x.GetValue(a, null)

just change a to content like this :

var pairs = props.Select(x => x.Name + "=" + x.GetValue(content, null)).ToArray();

content is name of your anonymous object .

But this solution you wrote not return dictionary . if you want dictionary do this :

public static Dictionary<string, string> convert(object content)
{

var props = content.GetType().GetProperties();
var pairDictionary = props.ToDictionary(x => x.Name,x=>x.GetValue(content,null)?.ToString());
return pairDictionary;
}

c# LINQ Dictionary of anonymous type values

If you do not return dictionary outside method you do not need to declare it.

    var dt = GetDataTable(@"SELECT COLUMN_NAME, IS_NULLABLE, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='{tableName}'");
var dict = dt?.AsEnumerable()?.ToDictionary(row => row.Field<string>(0), row => new { IS_NULLABLE = row.Field<bool>(1), DATA_TYPE = row.Field<string>(2), CHARACTER_MAXIMUM_LENGTH = row.Field<int>(3) });

you will get Dictionary<string, anonymous type>.

Than you can use your Type:

if(dict["key"].IS_NULLABLE) MessageBox.Show("yeah....");

Transform a Listobject of anonymous type to a Dictionarystring, SortedListDateTime, double

So basically you're asking how to unbox an anonymous type from object?

First of all, I recommend not using a List<object> and just ... creating a custom class.

public class SecurityScore {
public string Security { get; set; }
public DateTime Date { get; set; }
public int ZScore { get; set; }
}

However, if for whatever reason you need to do this, try this approach from Jon Skeet:

I've always known that it's perfectly easy to return an instance of an anonymous type by declaring that the method will return object. However, it hadn't occurred to me before today that you can actually cast back to that type afterwards. Of course, you can't just use a normal cast expression - that requires the name of the type to be known at compile-time. But you can do a cast in a generic method... and you can use type inference to supply a type argument... and two anonymous type instance creation expressions will use the same type within the same assembly if the order, names and types of the properties are the same.

If you want to explore his solution, check out his blog post on the subject.

For completeness, I will post his code here:

static class GrottyHacks
{
internal static T Cast<T>(object target, T example)
{
return (T) target;
}
}

class CheesecakeFactory
{
static object CreateCheesecake()
{
return new { Fruit="Strawberry", Topping="Chocolate" };
}

static void Main()
{
object weaklyTyped = CreateCheesecake();
var stronglyTyped = GrottyHacks.Cast(weaklyTyped,
new { Fruit="", Topping="" });

Console.WriteLine("Cheesecake: {0} ({1})",
stronglyTyped.Fruit, stronglyTyped.Topping);
}
}

I must admit that, while I don't really like the idea of boxing/unboxing an anonymous type, his approach is pretty awesome, and takes up relatively few lines of code.

So, now that I've given you a possible solution, I must ask -- why are you doing it this way, as opposed to creating a simple class?

Edit: Also for completeness, here's how I would implement your particular problem using Jon Skeet's solution:

void Main()
{
// Create a list of (boxed) anonymous objects
var securitiesBoxed = new List<object>() {
new { Security = "6752 JT", Date = DateTime.Parse("1/17/2011 12:00:00 AM"), zScore = 1 },
new { Security = "6753 JT", Date = DateTime.Parse("1/17/2011 12:00:00 AM"), zScore = 2 },
new { Security = "6754 JT", Date = DateTime.Parse("1/17/2011 12:00:00 AM"), zScore = 3 },
new { Security = "6752 JT", Date = DateTime.Parse("1/18/2011 12:00:00 AM"), zScore = 1 },
new { Security = "6753 JT", Date = DateTime.Parse("1/18/2011 12:00:00 AM"), zScore = 2 },
new { Security = "6754 JT", Date = DateTime.Parse("1/18/2011 12:00:00 AM"), zScore = 3 },
new { Security = "6752 JT", Date = DateTime.Parse("1/19/2011 12:00:00 AM"), zScore = 1 },
new { Security = "6753 JT", Date = DateTime.Parse("1/19/2011 12:00:00 AM"), zScore = 2 },
new { Security = "6754 JT", Date = DateTime.Parse("1/19/2011 12:00:00 AM"), zScore = 3 }
};

// Now, to convert to a Dictionary<string, SortedList<DateTime, double>>...
var securitiesUnboxed = securitiesBoxed.Select(x => Cast(x, new { Security = "", Date = new DateTime(), zScore = 0 }))
.GroupBy(x => x.Security)
.ToDictionary(x => x.Key, x => x.OrderBy(y => y.Date));
}

// This is the static method that will cast our anonymous type
internal static T Cast<T>(object target, T example)
{
return (T) target;
}

In LINQPad, the above code results in the following data:

linqified data

How can I convert anonymous object HTML attributes to a Dictionarystring, object

Looks like you might be applying the AnonymousObjectToHtmlAttributes either twice or to the wrong item.

Without more of your code, it's hard to tell

var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(new { id = "someID" });
attributes.Count = 1
attributes.Keys.First() = id

compared with

var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(new { id = "someID" }));
attributes.Count = 3
attributes.Keys.Join = Count,Keys,Values

When writing your overload, make sure your parameter is: object htmlAttributes for the new { } part with an overload with the IDictionary, eg:

Public static MvcHtmlString MyRadioButtonFor(..., object htmlAttributes)
{
return MyRadioButtonFor(...., HtmlHelper.AnonymousObjectToHtmlAttrbites(htmlAttributes);
}

public static MvcHtmlString MyRadioButtonFor(..., IDictionary<string, object> htmlAttributes)
{
htmlAttributes.Add("item", item);
return RadioButtonFor(..., htmlAttributes);
}

(just to be clear, never use My... - it's just for illustration)



Related Topics



Leave a reply



Submit