开发者

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

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜