我想将我的LiNQ结果转换为Dictionary

时间:2016-04-26 07:34:20

标签: c# linq

例如,这是我的查询

var result = (from D in dbcontext.NPPES where D.NPI == item.NPI && D.ProviderFirstName == item.FirstName && D.ProviderLastName == item.LastName select new 
{
D.firstname,
D.lastname,
D.NPI
}).FirstOrDefault()

现在我想将查询结果传递给迭代的函数,直到最后一列将结果转换为字典结果 我想要这样的结果

dt["firstname"] = "john"
dt["lastname"] = "khan"
dt["NPI"]="123456"

在这种情况下我该怎么做! Plz帮助

1 个答案:

答案 0 :(得分:4)

试试这段代码:

var result = new { firstname = "Mary", lastname = "Poppins", NPI = "NPI" };

var dictionary =
    result
        .GetType()
        .GetProperties()
        .Where(x => x.PropertyType == typeof(string))
        .Select(x => new { x.Name, Value = (string)x.GetValue(result) })
        .ToDictionary(x => x.Name, x => x.Value);

我明白了:

dictionary