Eliminar elementos en el diccionario (picadura, lista de objetos) [cerrado]

I am relatively new to programming. I have a dictionay(string, list of objects) and like to remove similar items in the list of objects.if there are no item in the list delete the entry in te dictionary.

Obj A properties - id,x,y

Dictionary(string, list(A)) dict = new Dictionary(string,list(A));

List(A) aList = new List(A);
aList.Add(new A(1,1,1));
aList.Add(new A(2,2,2));

List(A) bList = new List(A)
bList.Add(new A(1,1,1));

for(int i=dict.count-1; i>=0;i--)
    List(A) temp = List(A) dict[i].value;
    foreach(var entry in temp)

preguntado el 28 de mayo de 14 a las 12:05

this is not a valid C# code -

I do not have a complier at the moment. only notepad -

Not exactly clear, but this should be two passes, one to remove the "entry" and then an other to compact the dictionary removing any keys where that value is an empty list. -

@user3679184, and you decided to compile it trough the beautiful community of StackOverflow? :) -

can't modify the a collection you are iterating through either. Wait 'til you get back to your desk, all we can do with this is guess -

1 Respuestas

You want to loop through your list backwards or you will throw an error. You will always loop an array backwards to remove an item. You subtract 1 from the count because your array for example has 10 entries so the index is 0-9 not 1-10.

 //loop dict backwards so we can remove items
 for (int i = dict.Count - 1; i >= 0; i--)
            //convert the value to List<>
            List<TestObjs> objs = dict.ElementAt(i).Value as List<TestObjs>;

            //Loop List<> backwards so we can remove items
            for (int j = objs.Count - 1; j >= 0; j--)
                //if current id in list is value, remove it
                if (objs[j].id.Equals(1))

            //if list is now empty remove dict entry
            if (objs.Count.Equals(0))
                //use linq to grab the element at index and pass it's key to Remove

contestado el 28 de mayo de 14 a las 13:05

Noted. Thanks..am relatively new to this - user3679184

How can i delete away the entry in dictionary if there is no item in the list? - user3679184

Ok this will do what you need. Added comments - tsukasa

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.