Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return array of key=>value pair using Lambda in C#

Tags:

c#

.net

lambda

linq

I have the following Lambda expression that returns an array of result properties:

ViewBag.Items = db.Items.Select(m => new { m.Id, m.Column1, m.Column2 }).ToArray();

This works as expected, but I need the result to be a key=>value pair with Id being the key with Column1 & Column2 being the values. I've found examples on how to create a Dictionary, but not with isolating only specific columns in the results.

ViewBag.Items is localized for jQuery in the View using:

var _items = @Html.Raw(Json.Encode(ViewBag.Items));

How do I change the Lambda above to make an array of key=>value pairs?

like image 406
rwkiii Avatar asked Dec 07 '22 19:12

rwkiii


2 Answers

You could do it with ToDictionary:

db.Items.Select(m => new { m.Id, m.Column1, m.Column2 })
        .ToDictionary(x=>x.Id, x=>new {x.Column1, x.Column2});

That gives you Dictionary with Id as key and {Column1, Column2} as Values, if you want have Id as Value to consider good solution of HimBromBeere

like image 198
Maksim Simkin Avatar answered Dec 11 '22 07:12

Maksim Simkin


Where is the problem?

ViewBag.Items = db.Items.Select(m => new KeyValuePair<string, MyType>
    ( 
        m.Id, 
        new MyType { Column1 = m.Column1, Column2 = m.Column2 }
    )).ToArray();

But anyway a Dictionary is nothing but a list of KeyValuePair, so why not use it?

ViewBag.Items = db.Items.ToDictionary(
        m => m.Id, 
        m => new MyType { Column1 = m.Column1, Column2 = m.Column2 });

Of course you can also use a Dictionary<anonymous, anonymous>:

ViewBag.Items = db.Items.ToDictionary(
        m => m.Id, 
        m=> new { m.Column1, m.Column2 } );

but as you´re assigning this to a view I doubt you could use anonymous types here.

Using a Dictionary over an array of KeyValuePair has the advantage that duplicate keys are also checked. If you want to avoid this use ToLookup instead which will aloow duplicate keys.

like image 24
MakePeaceGreatAgain Avatar answered Dec 11 '22 07:12

MakePeaceGreatAgain