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

แชร์
ฝัง
  • เผยแพร่เมื่อ 27 ก.ย. 2024
  • 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.iamtimc...

ความคิดเห็น • 100

  • @lee1davis1
    @lee1davis1 11 หลายเดือนก่อน +8

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

    • @path_selector
      @path_selector 11 หลายเดือนก่อน +1

      constantly in more ways than one

    • @IAmTimCorey
      @IAmTimCorey  11 หลายเดือนก่อน +1

      I’m glad you are finding them useful.

  • @sparticus1701
    @sparticus1701 11 หลายเดือนก่อน +25

    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.

    • @IAmTimCorey
      @IAmTimCorey  11 หลายเดือนก่อน

      Thanks for sharing!

    • @trustingod0
      @trustingod0 14 วันที่ผ่านมา

      @sparticus1701 do you mind elaborating for us that are trying to learn the different applications of dictionaries. Thanks !

  • @dasfahrer8187
    @dasfahrer8187 11 หลายเดือนก่อน +5

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

    • @IAmTimCorey
      @IAmTimCorey  11 หลายเดือนก่อน +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 11 หลายเดือนก่อน

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

    • @purplepixeleater
      @purplepixeleater 9 หลายเดือนก่อน

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

  • @path_selector
    @path_selector 11 หลายเดือนก่อน +35

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

    • @IAmTimCorey
      @IAmTimCorey  11 หลายเดือนก่อน +20

      😂 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_ 11 หลายเดือนก่อน +2

      Unnaceptable

    • @path_selector
      @path_selector 11 หลายเดือนก่อน +4

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

  • @acodersjourney
    @acodersjourney 11 หลายเดือนก่อน +1

    Your videos are always helpful. Thanks!

    • @IAmTimCorey
      @IAmTimCorey  11 หลายเดือนก่อน

      You are welcome.

  • @gwog
    @gwog 11 หลายเดือนก่อน +2

    Great succinct lesson, thanks!

    • @IAmTimCorey
      @IAmTimCorey  11 หลายเดือนก่อน

      You are welcome.

  • @ScottAshmead
    @ScottAshmead 11 หลายเดือนก่อน +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  11 หลายเดือนก่อน

      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 11 หลายเดือนก่อน +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.

  • @HolyRamanRajya
    @HolyRamanRajya 11 หลายเดือนก่อน

    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  11 หลายเดือนก่อน +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 11 หลายเดือนก่อน

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

  • @rainbowsprinklez
    @rainbowsprinklez 11 หลายเดือนก่อน

    I LOVE the dictionary. I use it SO much!

    • @IAmTimCorey
      @IAmTimCorey  11 หลายเดือนก่อน

      Great!

    • @rainbowsprinklez
      @rainbowsprinklez 11 หลายเดือนก่อน

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

  • @Sammy2100
    @Sammy2100 11 หลายเดือนก่อน

    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 11 หลายเดือนก่อน

      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.

    • @trustingod0
      @trustingod0 14 วันที่ผ่านมา

      @Sammy2100 Duplicates of what? You mind giving me a little more explanation about what you are doing? Thanks !

  • @GodShiru
    @GodShiru 11 หลายเดือนก่อน +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  11 หลายเดือนก่อน

      Thanks for sharing!

    • @MrOudoum
      @MrOudoum 11 หลายเดือนก่อน +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 11 หลายเดือนก่อน +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 11 หลายเดือนก่อน +1

    Your next 10 video should be on concurrent dictionaries

    • @IAmTimCorey
      @IAmTimCorey  11 หลายเดือนก่อน

      Thanks for the suggestion.

  • @tmeryhewjsf35
    @tmeryhewjsf35 6 หลายเดือนก่อน

    Thanks for the information!

    • @IAmTimCorey
      @IAmTimCorey  6 หลายเดือนก่อน

      You are welcome.

  • @michaellyons7161
    @michaellyons7161 2 หลายเดือนก่อน

    Thanks for the video! how did Hogie get suggest for a correction? my spelling has crippled my code before

    • @IAmTimCorey
      @IAmTimCorey  2 หลายเดือนก่อน

      There is spell check now: th-cam.com/video/0NiHvdoMBO8/w-d-xo.htmlsi=EmK2DOKiGVPfaCL_&t=420

  • @b25671
    @b25671 4 หลายเดือนก่อน

    At our company we use dictionaries all the time.

  • @mogtabii
    @mogtabii 7 หลายเดือนก่อน

    thx

    • @IAmTimCorey
      @IAmTimCorey  7 หลายเดือนก่อน

      You are welcome.

  • @darkmalk94
    @darkmalk94 11 หลายเดือนก่อน

    Thank you M.Corey. Is the intelissense Copilot?

    • @IAmTimCorey
      @IAmTimCorey  11 หลายเดือนก่อน +1

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

  • @Richard-jm3um
    @Richard-jm3um 10 หลายเดือนก่อน

    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 9 หลายเดือนก่อน +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 9 หลายเดือนก่อน +1

      @@purplepixeleater Thanks!

  • @vinnypassmore5657
    @vinnypassmore5657 11 หลายเดือนก่อน

    Would you this as a default situation?

    • @IAmTimCorey
      @IAmTimCorey  11 หลายเดือนก่อน

      I am not sure what you are asking.

  • @Vastlee
    @Vastlee 11 หลายเดือนก่อน +3

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

    • @IAmTimCorey
      @IAmTimCorey  11 หลายเดือนก่อน

      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 6 หลายเดือนก่อน +1

    that is 100% how you spell hoagie

    • @IAmTimCorey
      @IAmTimCorey  6 หลายเดือนก่อน +1

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

  • @abhilashchalissery4637
    @abhilashchalissery4637 11 หลายเดือนก่อน

    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  11 หลายเดือนก่อน

      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 11 หลายเดือนก่อน

      @@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 11 หลายเดือนก่อน

      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 11 หลายเดือนก่อน

      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)

  • @onlydarthinvader
    @onlydarthinvader 11 หลายเดือนก่อน +3

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

    • @GodShiru
      @GodShiru 11 หลายเดือนก่อน +7

      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 11 หลายเดือนก่อน

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

    • @onlydarthinvader
      @onlydarthinvader 11 หลายเดือนก่อน

      @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 11 หลายเดือนก่อน +1

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

    • @Any1SL
      @Any1SL 11 หลายเดือนก่อน

      Beginners

  • @simon-white
    @simon-white 11 หลายเดือนก่อน +1

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

    • @IAmTimCorey
      @IAmTimCorey  11 หลายเดือนก่อน +2

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

  • @StevenWong1995
    @StevenWong1995 11 หลายเดือนก่อน +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  11 หลายเดือนก่อน +2

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

  • @ericritter46
    @ericritter46 6 หลายเดือนก่อน

    Billy Bob knows what life is about lmfao.

  • @LiveErrors
    @LiveErrors 11 หลายเดือนก่อน

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

  • @Allysson635
    @Allysson635 5 หลายเดือนก่อน

    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  5 หลายเดือนก่อน

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

  • @gnitin0384
    @gnitin0384 10 หลายเดือนก่อน

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

    • @IAmTimCorey
      @IAmTimCorey  10 หลายเดือนก่อน

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

  • @misc10k
    @misc10k 11 หลายเดือนก่อน

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

    • @philipyoxall5441
      @philipyoxall5441 11 หลายเดือนก่อน

      yes i would also like to know how you did this

    • @simon-white
      @simon-white 11 หลายเดือนก่อน

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

    • @IAmTimCorey
      @IAmTimCorey  11 หลายเดือนก่อน +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.

  • @75rxREDSTONE
    @75rxREDSTONE 11 หลายเดือนก่อน

    Why is the font scaling in visual studio so high?

    • @IAmTimCorey
      @IAmTimCorey  11 หลายเดือนก่อน +3

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

    • @kylekeenan3485
      @kylekeenan3485 11 หลายเดือนก่อน +2

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

    • @rafapioli75
      @rafapioli75 11 หลายเดือนก่อน

      ​@@kylekeenan3485Me too

  • @gikasmarkantonatos2168
    @gikasmarkantonatos2168 11 หลายเดือนก่อน

    Great as always. Thanks.

    • @IAmTimCorey
      @IAmTimCorey  11 หลายเดือนก่อน

      You are welcome.

  • @felipe.500
    @felipe.500 11 หลายเดือนก่อน

    Excellent

    • @IAmTimCorey
      @IAmTimCorey  11 หลายเดือนก่อน

      Thank you!