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 RemovingWorksIfConflictSituationsArise() { Dictionary<string, int> d = new Dictionary<string, int> { { "cats", 1 }, { "dogs", 1 }, { "mice", 1 } }; d.Remove("cats"); Assert.False(d.ContainsKey("cats")); Assert.True(d.ContainsKey("dogs")); Assert.Equal(2, d.Count); }
public void IsTrueIfRemovingAnItemWorks() { Dictionary<string, int> d = new Dictionary<string, int> { { "cats", 12 }, { "dogs", 13 } , { "mice", 15} }; d.Remove("cats"); Assert.False(d.ContainsKey("cats")); Assert.True(d.ContainsKey("dogs")); Assert.Equal(2, d.Count); }
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); }
public static void Main() { var graph = new Dictionary<string, List<string>>(); string line = Console.ReadLine(); while (line != string.Empty) { string[] connection = line.Split(' '); string first = connection[0]; string second = connection[1]; if (!graph.ContainsKey(first)) { graph[first] = new List<string>(); } graph[first].Add(second); // Loop? if (first != second) { if (!graph.ContainsKey(second)) { graph[second] = new List<string>(); } graph[second].Add(first); } line = Console.ReadLine(); } foreach (var node in graph) { Console.Write(node.Key + " -> "); foreach (string neighbors in node.Value) { Console.Write(neighbors + " "); } Console.WriteLine(); } }
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(); }
static void Main() { Dictionary<string, List<string>> graph = new Dictionary<string, List<string>>(); string line = Console.ReadLine(); while (line != string.Empty) { string[] connection = line.Split(' '); string first = connection[0]; string second = connection[1]; if (!graph.ContainsKey(first)) { graph[first] = new List<string>(); } graph[first].Add(second); if (!graph.ContainsKey(second)) { graph[second] = new List<string>(); } graph[second].Add(first); line = Console.ReadLine(); } foreach (var node in graph) { Console.Write(node.Key + " -> "); for (int i = 0; i < node.Value.Count; i++) { Console.Write(node.Value[i] + " "); } Console.WriteLine(); } }
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(); }
// 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 static void Main() { var chars = Console.ReadLine().ToCharArray(); var symbols = new Dictionary<char, int>(); foreach (var c in chars) { if (!symbols.ContainsKey(c)) { symbols[c] = 0; } symbols[c]++; } symbols.OrderBy(c => c.Key) .ToList() .ForEach(c => { Console.WriteLine("{0}: {1} time/s", c.Key, c.Value); }); }
public static void Main() { string input = Console.ReadLine(); Dictionary<char, int> charactersCount = new Dictionary<char, int>(); foreach (var character in input) { if (!charactersCount.ContainsKey(character)) { charactersCount[character] = 0; } charactersCount[character]++; } charactersCount .OrderBy(ch => ch.Key) .ToList() .ForEach(character => Console.WriteLine($"{character.Key}: {character.Value} time/s")); }
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() { 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 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); }
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(); }
public void ShouldNotBeTrueIfKeyIsntContained() { Dictionary<string, int> d = new Dictionary<string, int> { { "cats", 12 }, { "dogs", 13 } }; Assert.False(d.ContainsKey("mice")); }
public void ShouldBeTrueIfKeyContained() { Dictionary<string, int> d = new Dictionary<string, int> { { "cats", 12 }, { "dogs", 13 } }; Assert.True(d.ContainsKey("dogs")); Assert.True(d.ContainsKey("cats")); }
public void ReturnsTrueIfDictionaryContainsKey() { var data = new Dictionary<string, int> { { "first", 2 }, { "second", 3 } }; Assert.True(data.ContainsKey("second")); }
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; }
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; }
//вернуть слово из базы. Рандомно по списку private string WordBase(BackgroundWorker worker,Word word, Dictionary<int, Word> inter, List<string> listWords) { //создать регулярное выражение StringBuilder pattern = new StringBuilder(); string result = string.Empty; for (int i = 0; i < word.Length; i++) { if (inter.ContainsKey(i)) { //по координате в слове пересечения вернуть букву в пересикаемом слове int ind = inter[i].WordPointInt[word.WordPoint[i]]; if (inter[i].WordStr.Length!=0) { pattern.Append("[" + inter[i].WordStr[ind] + "]"); } else { pattern.Append("\\w{1}"); } } else { pattern.Append("\\w{1}"); } } Regex regex = new Regex(pattern.ToString()); List<string> listWordsTmp = new List<string>(listWords.ToArray()); bool exit = true; do { Random random = new Random(unchecked((int)(DateTime.Now.Ticks))); int randIndex = random.Next(listWordsTmp.Count); if (listWordsTmp.Count !=0) { if (regex.IsMatch(listWordsTmp[randIndex])) { exit = false; result = listWordsTmp[randIndex]; } } if (listWordsTmp.Count == 0) { return null; } listWordsTmp.RemoveAt(randIndex); if (worker != null) { worker.ReportProgress(100); } } while (exit); return result; }
private static Dictionary<string, List<string>> ReadGraph() { var graph = new Dictionary<string, List<string>>(); // Read a sequence of edges {parent, child} until an empty line is entered string line = Console.ReadLine(); while (line != string.Empty) { string[] edge = line.Split(' '); string parent = edge[0]; string child = edge[1]; if (!graph.ContainsKey(parent)) { graph[parent] = new List<string>(); } graph[parent].Add(child); // Loop? if (parent != child) { if (!graph.ContainsKey(child)) { graph[child] = new List<string>(); } graph[child].Add(parent); } line = Console.ReadLine(); } return graph; }