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. Thi开发者_开发技巧s 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);
_valueAdds.ToDictionary(t => t, t => false);
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:
gridItems = _valueAdds.Select(k => new { k })
.ToDictionary(t => t, t => false);
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:
gridItems = _valueAdds.ToDictionary(t => t, t => false);
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:
gridItems = _valueAdds.ToDictionary(p => p, p => false);
Assuming _valueAdds
is an IEnumerable<ValueAddedItemHelper>
you could do this:
gridItems = _valueAdds.ToDictionary(x => x, x => false);
Something like
var gridItems = _valueAdds.ToDictionary(k=>k,i=>false);
The Select(k => new { k })
is the problem; that creates an anonymous type with a property called k
. Just:
var gridItems = _valueAdds.ToDictionary(t => t, t => false);
精彩评论