The Dictionary Data Structure in C# in 10 Minutes or Less

Sdílet
Vložit
  • čas přidán 22. 10. 2023
  • A powerful list type in C# that is not often used is the dictionary. In this video, I want to quickly go over what it is and how to use it effectively so that you can add this data structure to your toolbox.
    Full Training Courses: IAmTimCorey.com
    Mailing List: signup.iamtimcorey.com/

Komentáře • 96

  • @sparticus1701
    @sparticus1701 Před 8 měsíci +21

    We use Dictionary quite a bit. It's very helpful when needing to map things. You can basically serialize/deserialize one to JSON and use it as a file format among other things.

  • @lee1davis1
    @lee1davis1 Před 8 měsíci +4

    Years ago I did tons of research on dictionaries and when I finally understood them I used them constantly.

    • @path_selector
      @path_selector Před 8 měsíci +1

      constantly in more ways than one

    • @IAmTimCorey
      @IAmTimCorey  Před 8 měsíci +1

      I’m glad you are finding them useful.

  • @acodersjourney
    @acodersjourney Před 7 měsíci +1

    Your videos are always helpful. Thanks!

  • @gwog
    @gwog Před 8 měsíci +2

    Great succinct lesson, thanks!

  • @gikasmarkantonatos2168
    @gikasmarkantonatos2168 Před 8 měsíci

    Great as always. Thanks.

  • @tmeryhewjsf35
    @tmeryhewjsf35 Před 3 měsíci

    Thanks for the information!

  • @rainbowsprinklez
    @rainbowsprinklez Před 8 měsíci

    I LOVE the dictionary. I use it SO much!

    • @IAmTimCorey
      @IAmTimCorey  Před 8 měsíci

      Great!

    • @rainbowsprinklez
      @rainbowsprinklez Před 8 měsíci

      @@IAmTimCorey Do you know if dictionaries are better to use over lists? Idk how much space it uses, but if you wanted to check if an object was in a list, the dictionaries O(1) time is way better than O(n)

  • @dasfahrer8187
    @dasfahrer8187 Před 8 měsíci +4

    Would be interested in seeing a follow-up comparing a list of tuples vs a dictionary.

    • @IAmTimCorey
      @IAmTimCorey  Před 8 měsíci +1

      There isn't really a good comparison here. A tuple holds two or more pieces of information. A dictionary is a key/value pair list.

    • @niennguyen410
      @niennguyen410 Před 8 měsíci

      @@IAmTimCorey Should return tuple or object (instance of class that hold vaule of result) in the async methods?

    • @purplepixeleater
      @purplepixeleater Před 5 měsíci

      depending on the complexity of the object you would choose the best solution for your software @@niennguyen410

  • @ScottAshmead
    @ScottAshmead Před 8 měsíci +1

    Would be great to see a follow up on this comparing Dictionary, List, and Datasets along with best use-case scenarios if you have the time..... Great vid

    • @IAmTimCorey
      @IAmTimCorey  Před 8 měsíci

      Thanks for the suggestion. Please add it to the list on the suggestion site so others can vote on it as well: suggestions.iamtimcorey.com/

    • @BrentHollett
      @BrentHollett Před 8 měsíci +2

      My Short Version:
      * ISet - Unordered unique data, usually for 'gather all the keys'.
      * IDictionary - Items with a defined key and no requirement to 'search' by other keys.
      * Datasets - Only when the data has an external source.
      * IQueryable - Multi-polar search of data, where there's either multiple possible keys or other data in the structure is relevant to lookups.
      * IList - Ordered set of non-unique data, generally where you only iterate over the whole collection.
      * IEnumerable - Unordered set of non-unique data, generally only using the interface when you receive data from one or more of the other types but don't want to constraint it.

  • @Sammy2100
    @Sammy2100 Před 8 měsíci

    Thanks for sharing Tim.
    I use a dictionary mostly for finding and counting duplicates.
    if (dictionaryObject.ContainsKey(key)
    dictionaryObject[key]++;
    else
    dictionaryObject.Add(key, 1);

    • @BrentHollett
      @BrentHollett Před 8 měsíci

      The .AddOrUpdate method of ConcurrentDictionary actually does this really well.
      "Add this if it doesn't exist (1), otherwise do this if it does and update the value (++)"
      even if you don't need concurrent access. It reduces the searching by half. I do kinda wish they'd include AddOrUpdate to the IDictionary interface.
      Otherwise in the above code you _should_ be using .TryGetValue but the implementation still uses two searches because you're using a value type.

  • @StevenWong1995
    @StevenWong1995 Před 8 měsíci +1

    Thanks Tim for this great video! But sometimes it's just difficult for me to decide in what situation I should use dictionary.

    • @IAmTimCorey
      @IAmTimCorey  Před 8 měsíci +2

      Use it when you are looking things up by the unique identifier.

  • @Allysson635
    @Allysson635 Před 2 měsíci

    That's an amazing video, thank you so much, it's being really useful as I'm preparing for some jobs interview. Btw is this auto suggestion an extension or plugin that you use? Is better than the default one that I have. Thanks!

    • @IAmTimCorey
      @IAmTimCorey  Před 2 měsíci

      I have GitHub Copilot installed. It is the one adding additional suggestions.

  • @felipe.500
    @felipe.500 Před 8 měsíci

    Excellent

  • @HolyRamanRajya
    @HolyRamanRajya Před 8 měsíci

    Since people use Entity Framework a lot now, I think it is more important to explain hashtables as a concept in general as DbSet derives from HashSet, and Dictionaries are special kinds of it. The reason for the performance bump with Dictionaries in scalable systems is primarily due to it being a selfadjusting Array(List) of LinkedLists. In my country, interview questions are directly asked on this concept of hashtables from 2nd year onwards as most startups heavily use Dictionaries or use Entity Framework.

    • @IAmTimCorey
      @IAmTimCorey  Před 8 měsíci +2

      Be careful, since Hashtables and other non-generics shouldn't be used in C# anymore: github.com/dotnet/platform-compat/blob/master/docs/DE0006.md

    • @HolyRamanRajya
      @HolyRamanRajya Před 7 měsíci

      @@IAmTimCoreyI was alluding to hashtable as a concept, not the class. And yes non-generics shouldn't be used.

  • @gnitin0384
    @gnitin0384 Před 7 měsíci

    Very useful video. Could we do sorting within values in a Dictionary?

    • @IAmTimCorey
      @IAmTimCorey  Před 7 měsíci

      The Dictionary lists the elements by their keys. You could sort the values into a new list, but not internal to the Dictionary.

  • @Richard-jm3um
    @Richard-jm3um Před 7 měsíci

    Quick question Tim! What would you suggest if I need to build a Dictionary-like structure but with repeated keys. E. G. if I need to keep track of more than one session for the same User ID ?

    • @purplepixeleater
      @purplepixeleater Před 5 měsíci +1

      you can store an array of times added to the dict and use that to make an identifier to the second repeated key like key1a key1b

    • @Richard-jm3um
      @Richard-jm3um Před 5 měsíci +1

      @@purplepixeleater Thanks!

  • @darkmalk94
    @darkmalk94 Před 8 měsíci

    Thank you M.Corey. Is the intelissense Copilot?

    • @IAmTimCorey
      @IAmTimCorey  Před 7 měsíci +1

      It is a mix of Intellicode and Copilot. The two work together.

  • @simon-white
    @simon-white Před 8 měsíci

    6:12 loving intellicode's concept of what makes a great wishlist 😂

    • @IAmTimCorey
      @IAmTimCorey  Před 8 měsíci +2

      Yeah, that was interesting. I regularly put vehicles and houses on my wishlist. For some reason, no one ever buys them for me.

  • @misc10k
    @misc10k Před 8 měsíci

    @IAmTimCorey what extension are you using that enables the auto-complete suggestions shown?

    • @philipyoxall5441
      @philipyoxall5441 Před 8 měsíci

      yes i would also like to know how you did this

    • @simon-white
      @simon-white Před 8 měsíci

      That'd probably be intellicode, can enable in the settings, don't believe any extensions are needed.

    • @IAmTimCorey
      @IAmTimCorey  Před 8 měsíci +1

      It is either Intellicode or it is GitHub Copilot. The two are so closely related that I'm often not sure where one stops and the other picks up.

  • @GodShiru
    @GodShiru Před 8 měsíci +1

    I actually use this all the time, to handle data that is usually presented in a table (especially in a database). Might not be quite as efficient as a 2D array, but it is much easier to develop methods around this, IMHO.
    I've actually created a few types around this.

    • @IAmTimCorey
      @IAmTimCorey  Před 8 měsíci

      Thanks for sharing!

    • @MrOudoum
      @MrOudoum Před 8 měsíci +1

      That is not true, it always depends on the use case.
      A dictionary uses a hash function to look up the keys this means it implements a hashtable.
      So if you perform many lookup based on the keys, then a dictionary might be faster compared to a 2D array.

    • @HolyRamanRajya
      @HolyRamanRajya Před 8 měsíci +1

      @@MrOudoum You took the words out of my mouth. Also want to add something that's not talked about enough in C# which is that Dictionaries and Hashsets are internally both hashtables which is the superior collection compared to Array-List and LinkedLists. Hashtables are essentially a selfadjusting array/List of multiple LinkedLists and plugs the weaknesses of both collections in regards to writing(adding/removal complexity) and reading.
      The Dbset Class used in Entity Framework is an extension of hashsets which is why LINQ works so well and .NET 7 onwards added specialized improvements between the interaction of Iqueryable, hashset around LINQ, internally using SIMD Vector hacks to extract even more performance. It's an interesting thing to explore and keep tabs on.

  • @Any1SL
    @Any1SL Před 8 měsíci +1

    Your next 10 video should be on concurrent dictionaries

  • @path_selector
    @path_selector Před 8 měsíci +28

    sorry 10 minutes 20 seconds you’ll have to update the title as this is clearly clickbait

    • @IAmTimCorey
      @IAmTimCorey  Před 8 měsíci +18

      😂 I know you are joking, but here is why I don’t. First, I didn’t say “less than 10 minutes”. So 10:59 would still be acceptable. Second, the bumper at the end is 21 seconds long.

    • @gracian_
      @gracian_ Před 8 měsíci

      Unnaceptable

    • @path_selector
      @path_selector Před 8 měsíci +2

      @@IAmTimCorey yup i was thinking this too haha just joking! thanks for your videos, seriously too useful

  • @mogtabii
    @mogtabii Před 3 měsíci

    thx

  • @LiveErrors
    @LiveErrors Před 7 měsíci

    i believe that some people use Dictionaries as their prefered method for writing Factories

  • @b25671
    @b25671 Před měsícem

    At our company we use dictionaries all the time.

  • @vinnypassmore5657
    @vinnypassmore5657 Před 8 měsíci

    Would you this as a default situation?

    • @IAmTimCorey
      @IAmTimCorey  Před 8 měsíci

      I am not sure what you are asking.

  • @75rxREDSTONE
    @75rxREDSTONE Před 8 měsíci

    Why is the font scaling in visual studio so high?

    • @IAmTimCorey
      @IAmTimCorey  Před 8 měsíci +3

      So that people can see it on video, even when they watch on their phone.

    • @kylekeenan3485
      @kylekeenan3485 Před 8 měsíci +2

      ​@@IAmTimCoreyThanks for doing so, I watch all your short videos on my phone.

    • @rafapioli75
      @rafapioli75 Před 7 měsíci

      ​@@kylekeenan3485Me too

  • @abhilashchalissery4637
    @abhilashchalissery4637 Před 8 měsíci

    I think we can use generic also right instead of int and string... Is that OK or should we stick defining data types... Is there any cons in using generic other than performance issue...

    • @IAmTimCorey
      @IAmTimCorey  Před 8 měsíci

      That is using generics. We have to define their specific type. We can choose which types, but we have to use some specified type.

    • @abhilashchalissery4637
      @abhilashchalissery4637 Před 8 měsíci

      @@IAmTimCorey
      Sir, is there a way to pull out data from the senario below.
      IDictionary obj = new Dictionary();
      string[] Sqlparms = { "@firstname", "@lastname" };
      string[] SqlValues = { "firstname", "lastname" };
      obj.Add(Sqlparms, SqlValues);
      how can i get the values from obj...

    • @abhilashchalissery4637
      @abhilashchalissery4637 Před 8 měsíci

      Basically i was trying to do this as below...
      public IDictionary SQLParams = new Dictionary();
      public string ExecuteInsert(string SP, object obj)
      {
      try
      {
      SQLParams = (IDictionary)obj;
      string result = "";
      using (SqlConnection con = Main_DB)
      {
      if (con.State == ConnectionState.Closed)
      {
      con.Open();
      }
      using (SqlCommand cmd = new SqlCommand(SP, con))
      {
      foreach (var item in SQLParams)
      {
      cmd.Parameters.AddWithValue(item.Key.ToString(), item.Value);
      }
      //cmd.Parameters.AddWithValue("@name", "abcd");
      //cmd.Parameters.AddWithValue("@mobileno", "1234");
      result = cmd.ExecuteScalar().ToString();
      }
      if (con.State == ConnectionState.Open)
      {
      con.Close();
      }
      }
      return result;
      }
      catch (System.Exception)
      {
      throw;
      }
      }

    • @Jeroen3001
      @Jeroen3001 Před 8 měsíci

      I would store your example in the following way:
      IDictionary obj = new Dictionary();
      obj.Add("@firstname", "firstname");
      obj.Add("@lastname","lastname");
      So, in general keep the key type simple (=value type like a string)

  • @ericritter46
    @ericritter46 Před 3 měsíci

    Billy Bob knows what life is about lmfao.

  • @Vastlee
    @Vastlee Před 8 měsíci +3

    "That is not often used..." WUT?

    • @IAmTimCorey
      @IAmTimCorey  Před 7 měsíci

      Compared to other data types that are similar. For instance, I might use a Dictionary once in a small application, but I'll use List dozens of times.

  • @joe_origlieri
    @joe_origlieri Před 3 měsíci

    that is 100% how you spell hoagie

    • @IAmTimCorey
      @IAmTimCorey  Před 3 měsíci

      😂 Thanks. It just looked weird. But once you start looking at a word, it almost always looks weird.

  • @onlydarthinvader
    @onlydarthinvader Před 8 měsíci +3

    This is the most beginner stuff possible, I am sorry, but who really needs this?

    • @GodShiru
      @GodShiru Před 8 měsíci +5

      Oh, sorry, from now on, he should only post stuff YOU'RE interested in... Sigh.
      You answered your own question : beginners need it, and his channel is about teaching everyone, not just people of your skill level.

    • @onlydarthinvader
      @onlydarthinvader Před 8 měsíci

      @@GodShiru you find it literally f...img everywhere. Don't worry, I unsubscribed, these videos are a waste of my time.

    • @onlydarthinvader
      @onlydarthinvader Před 8 měsíci

      @timmaes397 this channel used to different, now it is just beginner stuff that has nothing to give to basically anyone who is already working in the field and not occasional student coder

    • @caparn100
      @caparn100 Před 8 měsíci

      Oh yeah, I forgot no one is learning C# and no one is a beginner.

    • @Any1SL
      @Any1SL Před 8 měsíci

      Beginners