Returns an array of key => value pairs using Lambda in C #

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 as a key => value pair with the identifier being the key, with columns Column1 and Column2. I found examples on how to create a dictionary, but not isolate only specific columns in the results.

ViewBag.Items localized for jQuery in the view using:

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

How to modify Lambda above to create an array of key => value pairs?

+4
source share
2 answers

You can do this with ToDictionary:

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

Dictionary Id {Column1, Column2} , , Id Value HimBromBeere

+8

?

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

a Dictionary - , KeyValuePair, ?

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

, Dictionary<anonymous, anonymous>:

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

, , .

a Dictionary KeyValuePair , . , ToLookup, .

+6

Source: https://habr.com/ru/post/1667737/


All Articles