将<t>列入词典</t>

时间:2010-11-05 15:13:29

标签: c# linq generics dictionary

我有List<CustomObject> 它有3个属性 A,B,C 我需要的是将此List转换为Dictionary,结果如下所示

Dictionary<string,object>
(Property name) A = Value of A
(Property name) B = Value of B
(Property name) C = Value of C

请建议......

3 个答案:

答案 0 :(得分:5)

CustomObject instance = new CustomObject();
var dict = instance.GetType().GetProperties()
    .ToDictionary(p => p.Name, p => p.GetValue(instance, null));

答案 1 :(得分:2)

我找到了代码:)最初来自here

static T CreateDelegate<T>(this DynamicMethod dm) where T : class
{
  return dm.CreateDelegate(typeof(T)) as T;
}

static Dictionary<Type, Func<object, Dictionary<string, object>>> cache = 
   new Dictionary<Type, Func<object, Dictionary<string, object>>>();

static Dictionary<string, object> GetProperties(object o)
{
  var t = o.GetType();

  Func<object, Dictionary<string, object>> getter;

  if (!cache.TryGetValue(t, out getter))
  {
    var rettype = typeof(Dictionary<string, object>);

    var dm = new DynamicMethod(t.Name + ":GetProperties", rettype, 
       new Type[] { typeof(object) }, t);

    var ilgen = dm.GetILGenerator();

    var instance = ilgen.DeclareLocal(t);
    var dict = ilgen.DeclareLocal(rettype);

    ilgen.Emit(OpCodes.Ldarg_0);
    ilgen.Emit(OpCodes.Castclass, t);
    ilgen.Emit(OpCodes.Stloc, instance);

    ilgen.Emit(OpCodes.Newobj, rettype.GetConstructor(Type.EmptyTypes));
    ilgen.Emit(OpCodes.Stloc, dict);

    var add = rettype.GetMethod("Add");

    foreach (var prop in t.GetProperties(
      BindingFlags.Instance |
      BindingFlags.Public))
    {
      ilgen.Emit(OpCodes.Ldloc, dict);

      ilgen.Emit(OpCodes.Ldstr, prop.Name);

      ilgen.Emit(OpCodes.Ldloc, instance);
      ilgen.Emit(OpCodes.Ldfld, prop);
      ilgen.Emit(OpCodes.Castclass, typeof(object));

      ilgen.Emit(OpCodes.Callvirt, add);
    }

    ilgen.Emit(OpCodes.Ldloc, dict);
    ilgen.Emit(OpCodes.Ret);

    cache[t] = getter = 
      dm.CreateDelegate<Func<object, Dictionary<string, object>>>();
  }

  return getter(o);
}

对于给定类型:

class Foo
{
  public string A {get;}
  public int B {get;}
  public bool C {get;}
}

它产生一个等同于:

的委托
(Foo f) => new Dictionary<string, object>
  {
    { "A", f.A },
    { "B", f.B },
    { "C", f.C },
  };

免责声明:现在查看代码(未经测试)可能需要对valuetypes(而不仅仅是castclass)进行特殊处理。为读者练习。

答案 2 :(得分:0)

如果我理解你想要做什么,你必须在CustomObject上使用reflrecion获取属性名称然后只需创建字典:

dic.add(propertyName,value);