Question

I'm not the best at C# and I got a stack overflow exeption in this code:

private Dictionary<T, V> collection;
internal List<KeyValuePair<T, V>> ToList()
{
    return collection.ToList(); //the VS debugger breaked here
}

Here is the full class: http://pastebin.com/ji0Vrm0X
Hope someone can find the stack overflow exeption.

heres some more information :$

  internal QueuedDictionary<int, RoomUser> UserList
        {
            get
            {
                return userlist;
            }
        }

    internal List<RoomUser> GetRoomUsers()
    {
        List<KeyValuePair<int, RoomUser>> users = UserList.ToAList();

        List<RoomUser> returnList = new List<RoomUser>();
        foreach (KeyValuePair<int, RoomUser> pair in users)
        {
            if (!pair.Value.IsBot)
                returnList.Add(pair.Value);
        }

        return returnList;
    }
Was it helpful?

Solution

Explicitly create new KeyValuePair<T,V> elements from the dictionary, then make a list of it:

internal List<KeyValuePair<T, V>> ToList()
{
    return collection.Select(kvp => new KeyValuePair<T,V>(kvp.Key, kvp.Value).ToList(); 
}

Should perform the action you want.

Edit I would've expected your code to work as well. Could be that a Dictionary's .ToList() method does something similar to .Select(x => x.Value) as opposed to returning a List<KeyValuePair<X,Y>>.
But that'd just be my guess.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top