Check If Key Exists
Coddy'nin C# Journey'sinin Mantık & Akış bölümünün bir parçası — ders 48 / 66.
HashMap’te (C#’ta Dictionary) bir anahtarın var olup olmadığını kontrol etmek için ContainsKey() yöntemini kullanabilirsiniz.
İlk olarak, bir Dictionary oluşturun:
Dictionary<string, int> ages = new Dictionary<string, int>();Bazı anahtar-değer çiftleri ekleyin:
ages.Add("John", 25);
ages.Add("Mary", 30);Şimdi bir anahtarın var olup olmadığını kontrol edin:
bool exists = ages.ContainsKey("John");Yukarıdaki kodu çalıştırdıktan sonra, exists değişkeni true olacaktır.
Bunu bir koşul ifadesinde kullanabilirsiniz:
if (ages.ContainsKey("John"))
{
Console.WriteLine("John's age is in the dictionary");
}
else
{
Console.WriteLine("John's age is not in the dictionary");
}Görev
KolayCheckKeyExists adında iki parametre alan bir metot oluşturun:
- Bir
Dictionary<string, int>(dictionary) - Kontrol edilecek bir
string(key)
Metot, anahtarın sözlükte olup olmadığını kontrol etmeli ve yazdırmalı:
- anahtar bulunursa "Key exists"
- anahtar bulunmazsa "Key does not exist"
Kopya kağıdı
Dictionary'de bir anahtarın var olup olmadığını kontrol etmek için ContainsKey() metodunu kullanın:
Dictionary<string, int> ages = new Dictionary<string, int>();
ages.Add("John", 25);
ages.Add("Mary", 30);
bool exists = ages.ContainsKey("John"); // returns trueKoşullu ifadelerde kullanım:
if (ages.ContainsKey("John"))
{
Console.WriteLine("John's age is in the dictionary");
}
else
{
Console.WriteLine("John's age is not in the dictionary");
}Kendin dene
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
class Program
{
public static void CheckKeyExists(Dictionary<string, int> dictionary, string key)
{
// Kodunuzu buraya yazın
}
static void Main(string[] args)
{
Dictionary<string, int> inventory = new Dictionary<string, int>();
// Envanter girişi okunuyor - hem JSON formatını hem de satır satır formatı kabul eder
string firstLine = Console.ReadLine();
// Girişin JSON formatında olup olmadığını kontrol edin
if (firstLine != null && firstLine.StartsWith("{") && firstLine.EndsWith("}"))
{
try
{
// JSON girişini işle
string jsonContent = firstLine.Substring(1, firstLine.Length - 2);
// Tırnak içinde olmayan virgüllere göre ayır
string pattern = @",(?=(?:[^""]*""[^""]*"")*[^""]*$)";
string[] entries = Regex.Split(jsonContent, pattern);
foreach (string entry in entries)
{
// regex kullanarak anahtar ve değeri çıkar
Match match = Regex.Match(entry, @"""([^""]+)""\s*:\s*(\d+)");
if (match.Success)
{
string keyMatch = match.Groups[1].Value;
int valueMatch = int.Parse(match.Groups[2].Value);
inventory.Add(keyMatch, valueMatch);
}
}
// Reading the key to check directly
string keyToCheck = Console.ReadLine();
CheckKeyExists(inventory, keyToCheck);
}
catch (Exception ex)
{
Console.WriteLine($"Error parsing input: {ex.Message}");
}
}
else
{
// Process original line-by-line format
string line = firstLine;
// Read lines until an empty line is entered
while (!string.IsNullOrEmpty(line))
{
try
{
string[] parts = line.Split(':');
if (parts.Length == 2)
{
inventory.Add(parts[0], int.Parse(parts[1]));
}
}
catch (Exception ex)
{
Console.WriteLine($"Error parsing line: {ex.Message}");
}
// Read next line
line = Console.ReadLine();
}
// Reading the key to check
string keyToCheck = Console.ReadLine();
CheckKeyExists(inventory, keyToCheck);
}
}
}Bu ders kısa bir quiz içerir. Soruları yanıtlamak ve ilerlemeni kaydetmek için derse başla.
Mantık & Akış bölümündeki tüm dersler
1Multi-dimensional Arrays
2D Arrays BasicsDeclaring and Initializing 2DAccessing 2D Array ElementsNested Loops with 2D ArraysJagged ArraysCommon Matrix OperationsRecap - Multi-dimensional4Flow Control Techniques
Early ReturnsGuard ClausesJump Statements (goto)Break and ContinueFlatten Nested Conditionals7Logical Operators Advanced
Short-Circuit EvaluationConditional Logical OperatorsOperator PrecedenceRecap - Advanced Operators2Advanced Decision Making
Multiple ConditionsComplex Boolean LogicIf vs. Switch ComparisonNested Switch StatementsRecap - Advanced Decisions5Exception Handling
Try-Catch BasicsException TypesMultiple Catch BlocksWorking with FilesFinally BlockUsing vs. Try-FinallyCustom ExceptionsRecap - Error Handling3Loop Enhancements
Loop PerformanceIterating ComplexEach Loop TypeRefactoring LoopsRecap - Optimized Loops6Null Handling
Null Reference BasicsNullable Value TypesNull Checking PatternsDefensive ProgrammingRecap - Null Safety9HashMap Part 1
What is a HashMap?Declare a HashMapCheck If Key ExistsAccessing ValuesModifying DictionariesRecap - HashMap