[英]Return array of key=>value pair using Lambda in C#
I have the following Lambda expression that returns an array of result properties: 我有以下Lambda表达式,它返回一个结果属性数组:
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. 这按预期工作,但我需要结果是一个键=>值对,其中Id是关键,Column1和Column2是值。 I've found examples on how to create a Dictionary, but not with isolating only specific columns in the results.
我找到了关于如何创建Dictionary的示例,但没有找到仅隔离结果中的特定列的示例。
ViewBag.Items
is localized for jQuery in the View using: ViewBag.Items
在View中使用以下方式为jQuery本地化:
var _items = @Html.Raw(Json.Encode(ViewBag.Items));
How do I change the Lambda above to make an array of key=>value pairs? 如何更改上面的Lambda以生成一个key =>值对的数组?
You could do it with ToDictionary
: 你可以用
ToDictionary
做到这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 如果你想让Id作为Value来考虑HimBromBeere的良好解决方案,那么这会给你带有
Id
作为键的Dictionary
和{Column1, Column2}
作为值。
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? 但无论如何,
Dictionary
只不过是KeyValuePair
的列表,为什么不使用呢?
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>
: 当然你也可以使用
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. 在
KeyValuePair
数组上使用Dictionary
具有检查重复键的优点。 If you want to avoid this use ToLookup
instead which will aloow duplicate keys. 如果你想避免这种情况,请使用
ToLookup
来代替重复键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.