public void ShouldReturnCounterDifferentThan0() { var d = new Dictionary<string, int>(); d.Add("cats", 12); d.Add("dogs", 133); Assert.Equal(2, d.Count); }
public void ShouldReturnCounterNullForClear() { var d = new Dictionary<string, int>(); d.Add("cats", 12); d.Add("dogs", 133); d.Clear(); Assert.Equal(0, d.Count); }
public static Dictionary<string, State> GetStates() { var states = new Dictionary<string, State>(); var theState = new State("Montgomery", 123456, 123); states.Add("Alabama", theState); theState = new State("Juneau", 345234, 3234); states.Add("Alaska", theState); return states; }
// A dictionary is stored as a sequence of text lines //containing words and their explanations. //Write a program that enters a word and translates it by using the dictionary. Sample dictionary: // .NET – platform for applications from Microsoft //CLR – managed execution environment for .NET //namespace – hierarchical organization of classes static void Main(string[] args) { Dictionary<string, string> dict = new Dictionary<string, string>(); dict.Add(".NET", "platform for applications from Microsoft"); dict.Add("CLR", "managed execution environment for .NET"); dict.Add("namespace", "hierarchical organization of classes"); string word = Console.ReadLine(); if (dict.ContainsKey(word)) { Console.WriteLine(dict[word]); } }
public MainForm() { InitializeComponent(); dictionary = new Dictionary<string, string>(); FileStream file=null; StreamReader streamReader = null; try { file = new FileStream(Application.StartupPath + "\\OZHEGOV.TXT", FileMode.Open); streamReader = new StreamReader(file, ASCIIEncoding.Default); } catch (Exception) { MessageBox.Show("База ненайдена"); Application.ExitThread(); this.Close(); } string lineDictionary = string.Empty; dictionary = new Dictionary<string, string>(); while ((lineDictionary = streamReader.ReadLine()) != null) { string[] gg = Regex.Split(lineDictionary, @"\|\|\|"); dictionary.Add(gg[0], gg[1]); } streamReader.Close(); }
static void Main(string[] args) { Dictionary<String, Product> Catalog = new Dictionary<String, Product>(); Console.WriteLine("How many Products do you want to Catalog?"); int count; bool parse = Int32.TryParse(Console.ReadLine(), out count); while (!parse || count <= 0) { Console.WriteLine("Enter a valid input"); parse = Int32.TryParse(Console.ReadLine(), out count); } for (int i = 0; i < count;i++ ) { Console.WriteLine("Enter the Product Description :"); String descr = Console.ReadLine(); Console.WriteLine("Enter the Product Cost :"); string Cost = Console.ReadLine(); Console.WriteLine("Enter the Product Manufacturer:"); String manufacture = Console.ReadLine(); Console.WriteLine("Enter the Product Key:"); String key = Console.ReadLine(); Catalog.Add(key,new Product(descr, Cost, manufacture)); } Console.WriteLine("What Product-key you want to lookup?"); string response=Console.ReadLine (); Catalog[response].Print() ; }
static void Main(string[] args) { Dictionary<string, string> capitals = new Dictionary<string, string>(); capitals.Add("Alabama", "Montgomery"); capitals.Add("Alaska", "Juneau"); capitals.Add("Arizona", "Phoenix"); capitals.Add("Massachusetts", "Boston"); capitals.Add("Wyoming", "Cheyenne"); string capitalOfMass = capitals["Massachusetts"]; Console.WriteLine("The capital of Massachusetts is {0}", capitalOfMass); var theStates = State.GetStates(); var myState = theStates["Alaska"]; Console.WriteLine("the capital of Alaska is {0}, its population is {1}, and it is {2} square miles", myState.Captial, myState.Population, myState.Size ); }
public void ChecksIfAddFunctionWorksAfterRemove() { var data = new Dictionary<string, int> { { "first", 2 }, { "second", 3 } }; data.Remove("first"); data.Add("third", 6); Assert.True(data.ContainsKey("third")); Assert.False(data.ContainsKey("first")); }
public void AddWorksAfterRemove() { Dictionary<string, int> d = new Dictionary<string, int> { { "cats", 12 }, { "dogs", 13 }, { "mice", 15 } }; d.Remove("cats"); d.Add("bunnies", 19); Assert.False(d.ContainsKey("cats")); Assert.True(d.ContainsKey("dogs")); Assert.True(d.ContainsKey("bunnies")); Assert.Equal(3, d.Count); }
void Run() { Dictionary<int, int> myDict = new Dictionary<int, int>(); myDict.Add(0, 1); myDict.Add(1, 2); myDict.Add(2, 3); myDict.Add(3, 4); Console.WriteLine("Now it should print false"); Console.WriteLine(myDict.ContainsKey(4)); Console.WriteLine("Now it should print true"); Console.WriteLine(myDict.ContainsKey(3)); myDict.Remove(3); Console.WriteLine("Now it should print false"); Console.WriteLine(myDict.ContainsKey(3)); Console.WriteLine("Now it should print 2"); Console.WriteLine(myDict[1]); Dictionary<A, B> myDict2 = new Dictionary<A, B>(); A a1 = new A(); A a2 = new A(); myDict2.Add(a1, new B()); myDict2.Add(a2, new B()); Console.WriteLine("Now it should print false"); Console.WriteLine(myDict2.ContainsKey(new A())); Console.WriteLine("Now it should print true"); Console.WriteLine(myDict2.ContainsKey(a1)); myDict2.Remove(a1); Console.WriteLine("Now it should print false"); Console.WriteLine(myDict2.ContainsKey(a1)); Console.WriteLine("Now it should print \"Hello I'm B\""); myDict2[a2].f(); }
static void Main(string[] args) { Dictionary<int, Person> dic = new Dictionary<int, Person>(); Dictionary<string, Person> dic2 = new Dictionary<string, Person>(); Person p1 = new Person("Frey"); Person p2 = new Person("Leon"); dic.Add(p1.PersonId, p1); dic.Add(p2.PersonId, p2); foreach (var item in dic) { Console.WriteLine(item.Key + " " + item.Value.Name); } dic2.Add("Frey", new Person()); dic2.Add("Leon", new Person()); foreach (var item in dic2) { Console.WriteLine(item.Key + " " + item.Value.PersonId); } if (dic2.ContainsKey("Leon")) { Console.WriteLine("Key Leon Exists"); } Console.WriteLine("Delete Dictionary"); dic.Clear(); Console.WriteLine(); Console.WriteLine(""); foreach (var item in dic) { Console.WriteLine(item.Key + " " + item.Value.Name); } }
static void Main(string[] args) { Dictionary<char, string> certifications = new Dictionary<char, string>(); certifications.Add('P', "Passenger transport"); certifications.Add('H', "Hazardous materials"); certifications.Add('N', "Tank vehicles (liquids in bulk)"); certifications.Add('T', "Double/Triple trailers"); ShowCertifications(certifications); //search for certfications by key and confirm string theValue; //try get value //uses the out certifications.TryGetValue('H', out theValue); Console.WriteLine(theValue); if (certifications.ContainsKey('P')) Console.WriteLine("Has certfication 'P'"); //check certification for a specific value and confirm if (certifications.ContainsValue("Double/Triple trailers")) Console.WriteLine("Has certification 'T'"); //remove certification 'T' by key. certifications.Remove('T'); if (!certifications.ContainsValue("Double/Triple trailers")) Console.WriteLine("No longer has certification 'T'"); //remove all certifications certifications.Clear(); if (certifications.Count == 0) Console.WriteLine("All certifications removed"); Console.ReadLine(); }
static void Main(string[] args) { Dictionary<string, string> mydict = new Dictionary<string,string>(); mydict.Add(".NET", "platform for applications from Microsoft"); mydict.Add("CLR", "managed execution environment for .NET"); mydict.Add("namespace", "hierarchical organization of classes"); while (true) { Console.Write("Insert word: "); string currentWord = Console.ReadLine(); currentWord = currentWord.ToLower(); foreach (var item in mydict) { if (item.Key.ToLower() == currentWord) { Console.WriteLine("{0} - {1}", item.Key, item.Value); break; } } } }
public static void Main(string[] args) { Dictionary<string,int> dict=new Dictionary<string,int>(); dict.Add("one",1); dict.Add("two",2); dict.Add("three",3); dict.Add("four",4); dict.Remove("one"); Console.WriteLine ("Before contains"); Console.WriteLine(dict.ContainsKey("dsaf")); Console.WriteLine("Key Value Pairs after Dictionary related operations:\n"); foreach (var pair in dict) { Console.WriteLine("{0}, {1}", pair.Key, pair.Value); } dict.Clear (); List<string> strList = new List<string> (); strList.Add ("one"); strList.Add ("two"); strList.Add ("three"); strList.Add ("four"); strList.Add ("five"); strList.Insert (3, "great"); string[] newList = new string[3]{ "ten", "eleven", "twelve" }; strList.AddRange (newList); strList.InsertRange (3, newList); Console.WriteLine ("Output after all list related operations i.e. add, insert, addrange, insertrange,remove\n"); Console.WriteLine ("The list"); foreach (var i in strList) Console.WriteLine (i); }
/// <summary> /// Главная точка входа для приложения. /// </summary> static void Main() { Dictionary<string, string> dic = new Dictionary<string, string>(); dic.Add("Троу [Throw]", "Сроу [θrəʊ]" ); dic.Add("Парсе [Parse]", "Парс [pɑːrs]"); dic.Add("Матч [Math]", "Мэс [mæθ]" ); dic.Add("Джет [Get]", "Гет [ɡet]" ); dic.Add("Трэй [Try]", "Трай [traɪ]"; dic.Add("Анчекид [Unchecked]", "Анчект [ʌnˈtʃekt]"); dic.Add("Имплой [Employee]", "Имплойи [ɪmˈplɔɪiː]"); foreach (KeyValuePair<string, string> kvp in dic) { MessageBox.Show(string.Format("Правильное название {0} это {1}", kvp.Key, kvp.Value)); } }
static void Main(string[] args) { var namesAndAges = new Dictionary<string, int>/*(StringComparer.CurrentCultureIgnoreCase)*/ { {"Jeremy", 35} }; namesAndAges.Add("Josh", 25); namesAndAges["Kristin"] = 39; //namesAndAges.Add("Jeremy", 30); // an exception namesAndAges["Jeremy"] = 30; if (namesAndAges.ContainsKey("Caleb")) { var foo = namesAndAges["Caleb"]; // } foreach (var kvp in namesAndAges) { //kvp.Key //kvp.Value } foreach (var key in namesAndAges.Keys) { } foreach (var value in namesAndAges.Values) { } var count = namesAndAges.Count; if (namesAndAges.ContainsKey("Josh")) { namesAndAges.Remove("Josh"); } namesAndAges.Clear(); Console.ReadLine(); }
private static void Main() { string inputDictionary = SampleDictionary; string searchedWord = SampleSearchWord; string[] lines = inputDictionary.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries); Dictionary<string, string> dict = new Dictionary<string, string>(); foreach (var textLine in lines) { string[] parts = Regex.Split(textLine, @"\s*[^\w\s]\s+"); dict.Add(parts[0], parts[1]); } try { Console.WriteLine("Word: {0} -> explanation: {1}", searchedWord, dict[searchedWord]); } catch (KeyNotFoundException) { Console.WriteLine("There is no definition for this word."); } }
static void Main() { char[] symbols = Console.ReadLine().ToCharArray(); var symbolsCount = new Dictionary<char, int>(); foreach (var symbol in symbols) { if (!symbolsCount.ContainsKey(symbol)) { symbolsCount.Add(symbol, 0); } symbolsCount[symbol]++; } var sortedSymbolsCount = symbolsCount .OrderBy(sc => sc.Key); foreach (var symbolCount in sortedSymbolsCount) { Console.WriteLine("{0}: {1} time/s", symbolCount.Key, symbolCount.Value); } }
public void ChecksIfAddFunctionWorks() { var data = new Dictionary<string, int>(); data.Add("first", 3); Assert.Equal(1, data.Count); }
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker worker = sender as BackgroundWorker; if (e.Argument == null) { e.Cancel = true; return; } if (words != null) { //обнулить слова foreach (var item in words) { item.ClearStr(); } //слова из базы по длине Dictionary<int, List<string>> listWords = new Dictionary<int, List<string>>(); for (int i = 0; i < words.Count; i++) { if (!listWords.ContainsKey(words[i].Length)) { listWords.Add(words[i].Length, WordsCountKey(words[i].Length)); } } lock (treeWord=new TreeCross(words)) { treeWord.listWords = listWords; treeWord.SetCrossWords(); words = treeWord.GetWords(); } } e.Result = words; }
static void Main(string[] args) { Customer customer1 = new Customer() { ID = 101, Name = "Mark", Salary = 5000 }; Customer customer2 = new Customer() { ID = 102, Name = "Pam", Salary = 6500 }; Customer customer3 = new Customer() { ID = 103, Name = "John", Salary = 3500 }; Dictionary<int, Customer> dictionaryCustomers = new Dictionary<int, Customer>(); dictionaryCustomers.Add(customer1.ID, customer1); dictionaryCustomers.Add(customer2.ID, customer2); dictionaryCustomers.Add(customer3.ID, customer3); //for checking if key is not existing already if (!dictionaryCustomers.ContainsKey(customer1.ID)) { dictionaryCustomers.Add(customer1.ID, customer1); } //for checking if key exists if (dictionaryCustomers.ContainsKey(100)) { Customer checkIfIdExists = dictionaryCustomers[100]; } Customer customerSearchId = dictionaryCustomers[103]; //System.Console.WriteLine("ID = {0}, Name = {1}, Salary = {2}", customerSearchId.ID, customerSearchId.Name, customerSearchId.Salary); //Console.WriteLine(); //(works same as code in next line) foreach(KeyValuePair<int, Customer> CustomerKeyValuePair in dictionaryCustomers) foreach (var CustomerKeyValuePair in dictionaryCustomers) { Console.WriteLine("Key = " + CustomerKeyValuePair.Key); Customer cust = CustomerKeyValuePair.Value; Console.WriteLine ("ID = {0}, Name = {1}, Salary = {2} " , cust.ID ,cust.Name, cust.Salary); Console.WriteLine("-----------------------------------------"); } Console.WriteLine(); Console.WriteLine("Keys: "); foreach (var key in dictionaryCustomers.Keys) { Console.WriteLine(key); } Console.WriteLine(); Console.WriteLine("Values: "); foreach (Customer Value in dictionaryCustomers.Values) { Console.WriteLine("ID = {0}, Name = {1}, Salary = {2} ", Value.ID, Value.Name, Value.Salary); Console.WriteLine("-----------------------------------------"); } Console.ReadLine(); }
private Dictionary<string, bool> GetInCorrectWords(string filePath) { List<string> words = new List<string>(); StringBuilder s = new StringBuilder(); Stopwatch ws = new Stopwatch(); ws.Start(); char[] delimiterChars = { ' ', ',', '.', ':', '\t', '\n', '"', '!' }; if (!string.IsNullOrEmpty(filePath)) { using (StreamReader sr = new StreamReader(filePath)) { String line; while ((line = sr.ReadLine()) != null) { words.AddRange(line.Split(delimiterChars)); } } } ws.Stop(); Console.WriteLine("Time for reading incorrect file - " + ws.ElapsedMilliseconds + "ms"); ws.Restart(); Dictionary<string, bool> inCorrectWords = new Dictionary<string, bool>(); foreach (string word in words) { if (!inCorrectWords.ContainsKey(word) && !this.CheckWord(word)) { inCorrectWords.Add(word, true); } } ws.Stop(); Console.WriteLine("Time for finding incorrect words- " + ws.ElapsedMilliseconds + "ms"); Console.WriteLine("Incorrect words count - " + inCorrectWords.Count()); return inCorrectWords; }