Tech Off Thread

3 posts

Forum Read Only

This forum has been made read only by the site admins. No new threads or comments can be added.

C# equivalent to Python dict.fromkeys(ListofKeys,defaultvalue) ?

Back to Forum: Tech Off
  • User profile image
    androidi

    Essentially I want to do this:

    var myKeys = new List<MyKey>();
    var myDict = new Dictionary<MyKey, int>(myKeys.Distinct(),0); // where 0 is default value.

    edit: lol nevermind, I had somehow missed the obvious answer \/ - was too deep in the actual problem this dictionary was for that I managed overlook the ToDictionary!

  • User profile image
    Cupiditas

    Is this what you're aiming for?

    var myKeys = new List<MyKey>();
    var myDict = myKeys.Distinct().ToDictionary(x => x, x => 0);

    If you made any changes to the myKeys list they wouldn't be carried over to the dictionary, however any changes to the MyKey objects would be preserved.

  • User profile image
    androidi

    Thanks, all I can say is "DOH!" after all I've used ToList before and must've seen that but not really connected at any point that it could be used like that.

Conversation locked

This conversation has been locked by the site admins. No new comments can be made.