Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 我想将LiNQ结果转换为字典_C#_Linq - Fatal编程技术网

C# 我想将LiNQ结果转换为字典

C# 我想将LiNQ结果转换为字典,c#,linq,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() 现在我想将查询结果传递给函

例如,这是我的查询

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帮助

请尝试以下代码:

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);
我得到:


您使用的是哪个版本的c#?您可以使用的答案中提到的帮助器,因为您的结果是键入的,所以您只需编写代码,使用普通赋值即可。但是,如果您需要一些通用的东西,我会使用反射。@AshokRathod-该方法要求对象实现
IDictionary
。这与OP的要求不同。