function toDictionary
var propertyDictionary = object.ToDictionary(x => x.Property1, x => x.Property2);
function toDictionary
var propertyDictionary = object.ToDictionary(x => x.Property1, x => x.Property2);
convert dictionary to object c#
class ObjectToMapTo
{
public int ID;
public string Name;
public bool IsAdmin;
public override string ToString()
{
return $"(ID={ID} Name={Name} IsAdmin={IsAdmin})";
}
}
static object MapDictToObj(Dictionary<string, object> dict, Type destObject)
{
object returnobj = Activator.CreateInstance(destObject);
foreach (string key in dict.Keys)
{
object value = dict[key];
FieldInfo field = destObject.GetField(key);
if (field != null)
{
field.SetValue(returnobj, value);
}
}
return returnobj;
}
static void Main(string[] args)
{
Dictionary<string, object> dict = new Dictionary<string, object>();
dict["ID"] = 1000;
dict["Name"] = "This is a name";
dict["IsAdmin"] = true;
ObjectToMapTo obj = (ObjectToMapTo)MapDictToObj(dict, typeof(ObjectToMapTo));
Console.WriteLine(obj);
Console.ReadKey();
//Returns: (ID=1000 Name=This is a name IsAdmin=True)
}
c# object to dictionary
public static Dictionary<string, TValue> ToDictionary<TValue>(object obj)
{
var json = JsonConvert.SerializeObject(obj);
var dictionary = JsonConvert.DeserializeObject<Dictionary<string, TValue>>(json);
return dictionary;
}
c# new dictionary linq
var result =
// as Jon Skeet pointed out, OrderBy is useless here, I just leave it
// show how to use OrderBy in a LINQ query
myClassCollection.OrderBy(mc => mc.SomePropToSortOn)
.ToDictionary(mc => mc.KeyProp.ToString(),
mc => mc.ValueProp.ToString(),
StringComparer.OrdinalIgnoreCase);
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us