Linq returns IEnumerable <Dictionary <string, string >>

I need to return an IEnumerable of a dynamically created Dictionary.

pseudo code:

var x = from u in Users

select new dictionary<string, string>{
    Add("Name",u.Name),
    Add("LastName",u.LastName)
}

I tried many ways to get the pseudocode example above, but didn’t succeed ...

I am very grateful for your help.

+5
source share
4 answers
var x = from u in Users
        select new Dictionary<string, string> {
            { "Name", u.Name },
            { "LastName", u.LastName }
        };
+7
source

The error is "Unrecognized expression node" because LINQ to SQL is not able to turn the dictionary code into SQL. You can use AsEnumerable()to use LINQ to Objects instead of the compiler:

var x = from u in Users.AsEnumerable()
        select new Dictionary<string, string> {
            { "Name", u.Name },
            { "LastName", u.LastName }
        };
+4
source

- , .
User :

public class User
{
    public string Name { get; set; }
    public string LastName { get; set; }
}

:

var users = Users.Select(u => new User
            {
                Name = u.Name,
                LastName = u.LastName
            });

, , - :

var users = Users.Select(u => new { Name = u.Name, LastName = u.LastName });
+1
source

Conversion Method:

public Dictionary<string, string> ToPropertyDictionary(User theUser)
{
  Dictionary<string, string> result = new Dictionary<string, string>();
  result.Add("Name", theUser.Name);
  result.Add("LastName", theUser.Name);
  return result;
}

Called:

IEnumerable<Dictionary<string, string>> x =
  from u in Users.AsEnumerable()  //ensure local execution by using AsEnumerable
  select ToPropertyDictionary(u);
+1
source

All Articles