0

I am new to C# Programming and I don't know How to convert list to dictionary and vice versa and I am getting an runtime error called " StackOverflowException." Can anyone help me out or if anyone knows the solution please let me know.

Thanks in advance.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Assign2
{
    class Conversion
    {
        
        
    }
    class Program
    {
        static void Main(string[] args)
        {
            Conversion conversion = new Conversion();
            var list = new List<string> { "Demo1","Demo2","Demo3","Demo4"};
            var dictionary = conversion.ListToDictionary(list);
            foreach (var item in dictionary)
            {
                Console.WriteLine($"{item.Key}, {item.Value}");
            }
            var convertedList = conversion.DictionaryToList(dictionary);
            foreach (var item in convertedList)

            {
                Console.WriteLine($"{item}");
            }
            Console.ReadLine();
        }
    }
}
  • you dont need to use conversion, you can directly convert list to dictionary by specifying key. For example : var myDict = list.ToDictionary(keySelector: m => m.Id); – zaakm Aug 17 '22 at 08:28
  • This method calls itself `ListToDictionary` -> endless loop :-O – Markus Meyer Aug 17 '22 at 08:29
  • you can further look at this for inspiration : https://stackoverflow.com/questions/687313/building-a-dictionary-of-counts-of-items-in-a-list/687370 – zaakm Aug 17 '22 at 08:39

1 Answers1

1

ListToDictionary is calling itself and nothing is stopping it apparently. So it will call itself again and again and again... Until a stackoverflow exception because there will be too much call.

    public IDictionary<string,int> ListToDictionary(IList<string> list)
    {
        
            return ListToDictionary(list);
        
    }

The best way to convert a list to a dictionary is to use the "ToDictionary" extension method.

list.ToDictionary(item => item, item => item)

But in your case you're using a List of strings and a dictionary is a key/value set so what are you expecting in the end? Are the value in the list the keys or the values of the dictionary?

Arcord
  • 1,724
  • 1
  • 11
  • 16