Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why my List saves only last element and last occurance?

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 :enter image description here Any ideas?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading