11,570 questions
If you are interested in LINQ:
string[] arr = ["hello", "test", "hello", "raf"];
foreach( var g in arr.GroupBy( a => a ) )
{
Console.WriteLine( $"{g.Key}: {g.Count( )}" );
}
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
I am facing some difficulty when I am trying to find out the count of repeated words in C#.
Code:
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
//string[] _list = []; ;
List<string> a = new List<string>();
//bool inWord = false;
string[] arr = {"hello","test","hello","raf"};
int _counter = 0;
//int c = 0;
for (int i = 0; i<arr.Length; i++)
{
if (a.Contains(arr[i]))
{
//Console.WriteLine("second");
_counter++;
Console.WriteLine(arr[i] + " : " + _counter);
}
else
{
a.Add(arr[i]);
//Console.WriteLine("first");
_counter++;
Console.WriteLine(arr[i] + " : " + _counter);
//inWord = true;
//inWord = false;
}
_counter = 0;
}
}
}
Current output looks like:
hello : 1
test : 1
hello : 1
raf : 1
But I want:
hello : 2
test : 1
raf : 1
need help
If you are interested in LINQ:
string[] arr = ["hello", "test", "hello", "raf"];
foreach( var g in arr.GroupBy( a => a ) )
{
Console.WriteLine( $"{g.Key}: {g.Count( )}" );
}
This is also a way
//string[] _list = []; ;
Dictionary<string, int> a = new Dictionary<string, int>();
//bool inWord = false;
string[] arr = { "hello", "test", "hello", "raf" };
//int c = 0;
for (int i = 0; i < arr.Length; i++)
{
string key = arr[i];
if (a.TryGetValue(key, out int value))
{
a[key] = ++value;
Console.WriteLine($"{key} : {value}");
}
else
{
a.Add(key, 1);
Console.WriteLine($"{key} : 1");
}
}
Console.WriteLine($"--------------------------------");
foreach (var item in a)
{
Console.WriteLine($"{item.Key} : {item.Value}");
}