Domitius
Domitius

Reputation: 485

array to dictionary

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);

Upvotes: 3

Views: 4680

Answers (6)

Femaref
Femaref

Reputation: 61467

_valueAdds.ToDictionary(t => t, t => false);

Upvotes: 5

Marc Gravell
Marc Gravell

Reputation: 1063338

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);

Upvotes: 0

Richard Friend
Richard Friend

Reputation: 16018

Something like

var gridItems = _valueAdds.ToDictionary(k=>k,i=>false);

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1039120

Assuming _valueAdds is an IEnumerable<ValueAddedItemHelper> you could do this:

gridItems = _valueAdds.ToDictionary(x => x, x => false);

Upvotes: 0

xanatos
xanatos

Reputation: 111890

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);

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1502106

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);

Upvotes: 1

Related Questions