简体   繁体   中英

Return array of key=>value pair 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 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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM