0

How can I print the content of my dictionary and check when IDs are same. Like for example I get an Id like B83773, if it's appear in the dictionary I would print it on console.

Any kind of help will be super appreciated, I do not really understand the concept.

 static void Main(string[] args) { string ExtractIDFromFileName(string filename) { return filename.Split('_').Last(); } Dictionary<string, int> GetDictOfIDCounts() { List<string> allfiles = Directory.GetFiles("C:/filet/", "*.wish").Select(Path.GetFileNameWithoutExtension).ToList(); allfiles.AddRange(Directory.GetFiles("C:/filet/", "*.exe").Select(Path.GetFileNameWithoutExtension).ToList()); Dictionary<string, int> dict = new Dictionary<string, int>(); foreach (var x in allfiles) { string fileID = ExtractIDFromFileName(x); if (dict.ContainsKey(fileID)) { dict[fileID]++; } else { dict.Add(fileID, 1); } } return dict; } Console.WriteLine("" ); Console.ReadLine(); } 
9
  • Not sure what the question is here. You already have if (dict.ContainsKey(fileID)), what other than this is it that you require? Are you just missing a Console.WriteLine statement inside the { ... } for that if-statement, is that it? Commented Mar 22, 2019 at 11:18
  • Well I want to count whenever an ID appear more than 1 time and print them with a console.writeline, but I don't know how to call the Dictionnary Commented Mar 22, 2019 at 11:19
  • Typo alert: it's a dictionary - one "n" is QUITE enough ! Commented Mar 22, 2019 at 11:20
  • Not sure what you're asking here, what exactly do you mean by "call the dictionary"? dict.ContainsKey(fileID) checks if the key already exists in the dictionary, and returns true if it does, false if it doesn't. Commented Mar 22, 2019 at 11:20
  • are you looking for this: Console.WriteLine("{0}:{1}", fileID,dict[fileID] ); But I don't get why these up-votes for an unclear question Commented Mar 22, 2019 at 11:21

2 Answers 2

1

Unless I misunderstood your question, you can call your method GetDictOfIDCounts() and iterate thru it:

var result = GetDictOfIDCounts(); foreach (var item in result) { Console.WriteLine("{0} > {1}", item.Key, item.Value); } 

Key would be the string of your file ID and Value the count.

Sign up to request clarification or add additional context in comments.

Comments

0

How about something like this :

static void Main(string[] args) { var list = new List<string> {"a", "b", "c", "d", "a", "b", "a"}; var myDict = new Dictionary<string, int>(); foreach (var letter in list) { if (!myDict.ContainsKey(letter)) { myDict.Add(letter, 1); } else { myDict[letter]++; } } foreach (var letter in myDict.Keys) { Console.WriteLine($"{letter} : {myDict[letter]}"); } Console.ReadKey(); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.