2017-02-24 79 views
3

我需要将列表转换为字典。这可以在C#中使用以下语法使用字符串转换列表为字典表达式c#

var dictionary = myList.ToDictionary(e => e.Id); 

做我不知道id字段的名字,因为我创造了一些代码,通过对象及其子对象/列表进行迭代,并将它们连接到我的dbcontext。

我已经得到了代码,以确定这是我的键值属性的名称,但对于测试我可以只使用“ID”(其他人可能有所不同)

,所以我需要基本创建这个字符串“ c => e.Id“到Func,但我不确定什么参数是什么Expression对象。

到目前为止,我有这个

public static Expression<Func<T, bool>> strToFunc<T>(string propName) 
{ 
    Expression<Func<T, bool>> func = null; 

     var prop = typeof(T).GetProperty(propName); 
     ParameterExpression tpe = Expression.Parameter(typeof(T)); 
     var left = Expression.Property(tpe, prop); 


    return func; 
} 

有人谁是在表达式中的专家,会很感激你的帮助。

在此先感谢

+0

也许看看[动态LINQ(https://dynamiclinq.codeplex.com/)。这可能就是你正在寻找的东西。 – Mats391

+1

在测试程序中写入'Expression > tmp = x => x.SomeProperty;',您将能够在调试器中查看'tmp'对象,这将帮助您找出什么你需要的东西。另外,为什么你的函数是''如果你试图做一个表达式,我会期望'' –

+1

如果我误解了这个问题,请纠正我,但是如果你知道包含键值的属性的名字,什么阻止你做'var dictionary = myList.ToDictionary(e => e.GetType()。GetProperty(propName).GetValue(e));'? – Innat3

回答

0

如果我明白你的问题,这是我会怎么做,希望它可以帮助一些如何若不。

public static Dictionary<object, TValue> GenericToDictionary<TValue>(this IEnumerable<TValue> source, string propName) 
{ 
    Dictionary<object, TValue> result = new Dictionary<object, TValue>(); 
    foreach (var obj in source) 
    { 
     result[obj.GetType().GetProperty(propName).GetValue(obj)] = obj; 
    } 
    return result; 
} 
0

如果你有属性名称作为字符串,你可以试试这个。

public static Dictionary<string, T> ListToDictionary<T>(string propertyName, List<T> list) 
    { 
     Func<T, string> func = obj => typeof(T).GetProperty(propertyName).GetValue(obj) as string; 
     return list.ToDictionary(func); 
    } 

否则你可以通过表达一个lambda:

class Person 
    { 
     public int ID { get; set; } 
     public string Name { get; set; } 
    } 

    public static void DoSomething() 
    { 
     var people = new List<Person>(); 
     var dict = people.ToDictionary(p => p.ID); 
    }