Search code examples
c#dictionaryordereddictionary

Get value of an OrderedDictionary


I cannot manage to find values from my OrderedDictionary, I was following several posts on the stack, so I don't see what I am not doing good?

private List<IfcElement> readListParamFromList(Int32 index, OrderedDictionary ifcList)
{
    List<IfcElement> retour = new List<IfcElement>();
    if (this.ListParams[index] != "")
    {
        string[] listStrings = this.ListParams[index].Split(',');

        foreach (string idString in listStrings)
        {
            long idElt = -1;
            idElt = IfcGlobal.GetIdFromIfcString(idString);
            try
            {
                object objectFound = (IfcElement)ifcList[(object)idElt];
                IfcElement newElt = (IfcElement)objectFound;
                retour.Add(newElt);
                this.addChildren(newElt);
            }
            catch
            {
                this.ErrorFound = true;
                this.ListItemsNotFound.Add(idElt);
            }
        }
    }
    return retour;
}

Here I find IdElt=104. Then I checked in debug, my OrderedDictionary has an element inside with Key=104, and object is present in value, but the line object objectFound = (IfcElement)ifcList[(object)idElt]; is always returning null. Is there something wrong with my syntax? Maybe it helps, I add the way I add elements in my dictionary :

public class GroupedListElements
{
    public string Type { get; set; } = "";
    public OrderedDictionary ListIfcElements = new OrderedDictionary();
    public GroupedListElements()
    {

    }
}

GroupedListElements newGroupList = new GroupedListElements { Type = 

newElt.GetType().Name };
newGroupList.ListIfcElements.Add(newElt.ID, newElt);
this.ListGroupped.Add(newGroupList);

Solution

  • I think the problem is that by casting to (object) before retrieving the object from the ordered dictionary, the dictionary tries to locate the key based on Object.Equals(). Object.Equals returns true if the boxed long objects have the same reference (i.e. the ReferenceEquals method returns true). If you don't mind using strings instead of longs as keys, I would recommend to do so.

    To see in detail what's going wrong with your code, maybe replace the following line

    object objectFound = (IfcElement)ifcList[(object)idElt];
    

    with

    object objectKey = (object)idElt;
    object objectFound = (IfcElement)ifcList[objectKey];
    

    And then look in the immediate Window of the debugger whether objectKey.ReferenceEquals(x) returns true for any x in

    ifcList.Keys