开发者

Linq returning a IEnumerable<Dictionary<string,string>>

开发者 https://www.devze.com 2023-01-09 13:41 出处:网络
I need to return an IEnumerable of a dynamically created Dictionary. pseudo code: var x = from u in Users

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

pseudo code:

var x = from u in Users

select ne开发者_如何学Cw dictionary<string, string>{
    Add("Name",u.Name),
    Add("LastName",u.LastName)
}

I've been trying many ways to get the pseudo code example above but no success...

I would really appreciate your help.


var x = from u in Users
        select new Dictionary<string, string> {
            { "Name", u.Name },
            { "LastName", u.LastName }
        };


The "Unrecognized expression node" error you're getting is because LINQ to SQL is failing to turn the dictionary-related code into SQL. You can use AsEnumerable() to make the compiler use LINQ to Objects instead:

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


That is poor use of a dictionary - you're only using it as a property bag, and create as many dictionaries as users.
A better use of the language would be creating your own User class with these properties and use that:

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

And the query:

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

If you'll only use the collection whiting your method, another option is to create an anonymous class:

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


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 by:

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

精彩评论

暂无评论...
验证码 换一张
取 消