数组到字典
我试图将此 _valueAdds = List
放入 gridItems
(Dictionary
),其中 _valueAdds
为键和所有值均为 false
。但我不知道如何用 Lamda 做到这一点。这就是我在下面走了多远。我确实成功地用 while 循环做到了这一点,但想学习用 Lamda 做到这一点
gridItems = new Dictionary<ValueAddedItemHelper, bool>();
gridItems = _valueAdds.Select(k => new { k }).ToArray().ToDictionary(t => t, false);
I'm trying to get this _valueAdds = List<ValueAddedItemHelper>
into gridItems
(Dictionary
) with _valueAdds
being the Key and all the values being false
. But I'm not sure how to do this with Lamda. This how far I got below. I did succeed in doing it with a while loop but would like learn to do it with Lamda
gridItems = new Dictionary<ValueAddedItemHelper, bool>();
gridItems = _valueAdds.Select(k => new { k }).ToArray().ToDictionary(t => t, false);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您需要提供 lambda 表达式作为第二个参数(或以其他方式创建委托,但 lambda 表达式是最简单的)。请注意,对
ToArray
的调用不是必需的,您要创建的空字典也不是必需的。只是使用:我不清楚为什么你在这里使用匿名类型......特别是,不会是一个
ValueAddedItemHelper
。您是否需要投影?也许只是:You need to provide a lambda expression as the second argument (or create the delegate some other way, but a lambda expression will be simplest). Note that the call to
ToArray
isn't required, and nor is the empty dictionary you're creating to start with. Just use:It's not clear to me why you're using an anonymous type here though... in particular, that won't be a
ValueAddedItemHelper
. Do you need the projection at all? Perhaps just:您不需要 ToArray().ToDictionary()。您只需执行 ToDictionary() 即可。而且你不需要第一行。第二行将创建并填充字典。
代码:
You don't need a ToArray().ToDictionary(). You can simply do a ToDictionary(). And you don't need the first line. The second line will create and fill the dictionary.
The code:
假设
_valueAdds
是IEnumerable
你可以这样做:Assuming
_valueAdds
is anIEnumerable<ValueAddedItemHelper>
you could do this:像这样的东西
Something like
Select(k => new { k })
是问题所在;它创建一个带有名为k
的属性的匿名类型。只是:The
Select(k => new { k })
is the problem; that creates an anonymous type with a property calledk
. Just: