-1

For example this is my query

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()

Now i want to pass my query result to function which iterates till last column converts the result into Dictionary result i want my result like this

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

What should i do in this case! Plz Help

Khan
  • 41
  • 6
  • 2
    [ToDictionary](https://msdn.microsoft.com/en-us/library/bb549277(v=vs.110).aspx) – Salah Akbari Apr 26 '16 at 07:36
  • which version of c# are you using? – Mukund Apr 26 '16 at 07:38
  • 1
    you can use mentioned helper that is in the answer of [this question](http://stackoverflow.com/questions/11576886/how-to-convert-object-to-dictionarytkey-tvalue-in-c) – Ashok Rathod Apr 26 '16 at 07:38
  • Since your result is typed you can simply write the code to do this using plain assignments. If however you need something generic I would use reflection. – cleftheris Apr 26 '16 at 08:29
  • @AshokRathod - That method requires that the object implement `IDictionary`. That's different from the OP's requirement. – Enigmativity Apr 26 '16 at 08:34

1 Answers1

4

Try this code:

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);

I get:

dictionary

Enigmativity
  • 113,464
  • 11
  • 89
  • 172