How to filter a List<Dictionary<string, Object>?

Asked

Viewed 330 times

4

I have a list variableMatriz that is a List>.

She has 108 items.

The listMatriz[0] looks like this:

inserir a descrição da imagem aqui

What I wanted was for the list variableMatrizFiltrada to come only with items from the Triz list whose COD_OCUPACAO = 1 && COD_NIVEL = 1

I tried in many ways, for example:

var listaMatrizFiltrada = listaMatriz.GroupBy(i => i.ElementAt(0).Value == 1 && i.ElementAt(4).Value == 1).Where(group => @group.Any()).Select(g => g.First()).ToDictionary(kvp => kvp.Keys, kvp => kvp.Values);

But it didn’t filter correctly. This code I found on the internet, but I still don’t understand exactly how each excerpt works (Groupby, Where, etc).

  • This really doesn’t make much sense. Try to show a larger context of how you are using this dictionary list. When there is a collection inside the other is a little more complicated even. And I’m thinking that the alternative solution I gave in the other question using ExpandoObject can be more suitable and simpler to manipulate. I can’t guarantee because I don’t know exactly all your needs. Are you trying to group something together or was that trying to solve the simple filter problem? You can ensure that all dictionaries have these two filter keys?

  • Thank you again @bigown, before replying to you I went to test the Gypsy solution and it really worked. I used groupby only to solve the filter problem and all dictionaries have that two keys yes.

  • Could create a matrix, second dimension, in case in Visual Basic would be Dim listaMatrizFiltrada As Object(,) = {{item1, item2}, {item3, item4}} etc....

1 answer

4


You can simplify it a lot more:

var listaMatrizFiltrada = listaMatriz
                          .Where(item => item["COD_OCUPACAO"] == 1 &&         
                                           item["COD_NIVEL"] == 1)
                          .ToList();

Like ListaMatriz is a list of dictionaries, item will be a Dictionary<string, object>, so I can use indexes like item["COD_OCUPACAO"] and item["COD_NIVEL"].

I’m guessing that this is an extract from a database, and that all dictionaries on the list have the same indexes.

  • 2

    Perfect! It was just that! The only thing I needed to do was to convert item["COD_OCUPACAO"] and item["COD_NIVEL"] into integers and it worked there.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.