So I have a code here:
string word = "abba";
Counter(word);
public static List<Occur> Counter(string word)
{
Occur Oc = new Occur();
var ListNubmersOfWord = new List<Occur>();
foreach (char c in word)
{
Oc.Letter = c;
Oc.Number = word.Where(x => x == c).Count();
ListNubmersOfWord.Add(Oc);
}
foreach(Occur item in ListNubmersOfWord)
{
Console.WriteLine(string.Join(" ", $"{item.Letter} {item.Number}"));
}
return ListNubmersOfWord;
}
Here is Occur Class:
public class Occur
{
public int Number { get; set; }
public char Letter { get; set; }
}
And the problem is that for some reason list "ListNubmersOfWord" only saves last letter and last occurrence. The outcome is :
Any ideas?
>Solution :
In each iteration of the loop, you are setting Letter and Number to the same object reference. Try to instantiate new object inside the body of the foreach loop:
foreach (char c in word)
{
Occur Oc = new Occur
{
Letter = c,
Number = word.Where(x => x == c).Count()
};
ListNubmersOfWord.Add(Oc);
}