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...
Years ago I did tons of research on dictionaries and when I finally understood them I used them constantly.
constantly in more ways than one
I’m glad you are finding them useful.
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.
Thanks for sharing!
@sparticus1701 do you mind elaborating for us that are trying to learn the different applications of dictionaries. Thanks !
Would be interested in seeing a follow-up comparing a list of tuples vs a dictionary.
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.
@@IAmTimCorey Should return tuple or object (instance of class that hold vaule of result) in the async methods?
depending on the complexity of the object you would choose the best solution for your software @@niennguyen410
sorry 10 minutes 20 seconds you’ll have to update the title as this is clearly clickbait
😂 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.
Unnaceptable
@@IAmTimCorey yup i was thinking this too haha just joking! thanks for your videos, seriously too useful
Your videos are always helpful. Thanks!
You are welcome.
Great succinct lesson, thanks!
You are welcome.
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
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/
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.
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.
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
@@IAmTimCoreyI was alluding to hashtable as a concept, not the class. And yes non-generics shouldn't be used.
I LOVE the dictionary. I use it SO much!
Great!
@@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)
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);
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.
@Sammy2100 Duplicates of what? You mind giving me a little more explanation about what you are doing? Thanks !
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.
Thanks for sharing!
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.
@@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.
Your next 10 video should be on concurrent dictionaries
Thanks for the suggestion.
Thanks for the information!
You are welcome.
Thanks for the video! how did Hogie get suggest for a correction? my spelling has crippled my code before
There is spell check now: th-cam.com/video/0NiHvdoMBO8/w-d-xo.htmlsi=EmK2DOKiGVPfaCL_&t=420
At our company we use dictionaries all the time.
Great!
thx
You are welcome.
Thank you M.Corey. Is the intelissense Copilot?
It is a mix of Intellicode and Copilot. The two work together.
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 ?
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
@@purplepixeleater Thanks!
Would you this as a default situation?
I am not sure what you are asking.
"That is not often used..." WUT?
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.
that is 100% how you spell hoagie
😂 Thanks. It just looked weird. But once you start looking at a word, it almost always looks weird.
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...
That is using generics. We have to define their specific type. We can choose which types, but we have to use some specified type.
@@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...
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;
}
}
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)
This is the most beginner stuff possible, I am sorry, but who really needs this?
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.
@@GodShiru you find it literally f...img everywhere. Don't worry, I unsubscribed, these videos are a waste of my time.
@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
Oh yeah, I forgot no one is learning C# and no one is a beginner.
Beginners
6:12 loving intellicode's concept of what makes a great wishlist 😂
Yeah, that was interesting. I regularly put vehicles and houses on my wishlist. For some reason, no one ever buys them for me.
Thanks Tim for this great video! But sometimes it's just difficult for me to decide in what situation I should use dictionary.
Use it when you are looking things up by the unique identifier.
Billy Bob knows what life is about lmfao.
😆
i believe that some people use Dictionaries as their prefered method for writing Factories
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!
I have GitHub Copilot installed. It is the one adding additional suggestions.
Very useful video. Could we do sorting within values in a Dictionary?
The Dictionary lists the elements by their keys. You could sort the values into a new list, but not internal to the Dictionary.
@IAmTimCorey what extension are you using that enables the auto-complete suggestions shown?
yes i would also like to know how you did this
That'd probably be intellicode, can enable in the settings, don't believe any extensions are needed.
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.
Why is the font scaling in visual studio so high?
So that people can see it on video, even when they watch on their phone.
@@IAmTimCoreyThanks for doing so, I watch all your short videos on my phone.
@@kylekeenan3485Me too
Great as always. Thanks.
You are welcome.
Excellent
Thank you!