Home > Software engineering >  How to filter list of dictionary values with criteria
How to filter list of dictionary values with criteria

Time:10-15

At first, I have some DataRows into Dictionary. I made an example to show how it's made and how I could make the same linq query with datatable.

I'd like to search by example the list of records having the UTI_SURNAME value beginning with "A" and with profile code 2.

With the datatable, I would execute this code :

DataTable dt = new DataTable();
dt.Columns.Add("UTI_ICODE" , typeof(int));  
dt.Columns.Add("UTI_NAME", typeof(string));
dt.Columns.Add("UTI_SURNAME", typeof(string));
dt.Columns.Add("PROFIL_ICODE", typeof(int));

dt.Rows.Add(1, "Name Arnaud", "Arnaud", 1);
dt.Rows.Add(2, "Name Armand", "Armand", 2);
dt.Rows.Add(3, "Name Armelle", "Armelle", 2);
dt.Rows.Add(4, "Name Basile", "Basile", 1);
dt.Rows.Add(5, "Name Bernard", "Bernard", 2);

List<Dictionary<string, object>> lstUTI = dt.AsEnumerable().Select(
    row => dt.Columns.Cast<DataColumn>().ToDictionary(
        column => column.ColumnName,
        column => row[column]
    )).ToList();

dt.AsEnumerable().Where(x => x.Field<string>("UTI_SURNAME").StartsWith("A") && x.Field<int>("PROFIL_ICODE") == 2).ToList();

and the result from dt would be:
example result

Now, I'd like to make a query to have the same result with the list lstUTI in this way :

lstUTI.Where(...).ToList();

and I'd like the result as this:
expected result

How can I do it with LINQ ?

CodePudding user response:

You can do that quite easily by using the index operator of the dictionary:

var result = lstUTI.Where(dict => 
                    dict["UTI_SURNAME"].ToString().StartsWith("A")
                    && (int)dict["PROFIL_ICODE"] == 2);

If you want to print out the result:

foreach (Dictionary<string, object> row in result)
{
    Console.WriteLine(new string('=', 10));
    foreach (KeyValuePair<string, object> cell in row)
    {
        Console.WriteLine($"{cell.Key}: {cell.Value}");
    }
}

then the output will look like this:

UTI_ICODE: 2
UTI_NAME: Name Armand
UTI_SURNAME: Armand
PROFIL_ICODE: 2
==========
UTI_ICODE: 3
UTI_NAME: Name Armelle
UTI_SURNAME: Armelle
PROFIL_ICODE: 2

I want to emphasize that the above solution is not bullet-proof. You should check the existence of the key before you perform any action on the value.

  • Related