lundi 20 juin 2022

LINQ - Dynamically Invoke ToDictionary

Is there a way in .Net to dynamically invoke ToDictionary(<lambda key>, <lambda val>) to reduce boilerplate of returning a Dictionary when running LINQ expressions.

C# Example:

Dictionary<string, object> d_filt;

Dictionary<string, object> d_in = new Dictionary<string, object>();
d_in.Add("k1", 4);
d_in.Add("k2", 3);
d_in.Add("k3", 2);
d_in.Add("k4", 1);

// Current Expression:
d_filt = d_in.Where(p => p.value > 2)
             .ToDictionary(p => p.Key, p => p.Value);

// Preferred Expression:
d_filt = linq2Dict(d_in.Where(p => p.value > 2));

Where linq2Dict(<LinqObj>) is a helper that will dynamically invoke the ToDictionary(..) method.

I have tried Reflection library but it appears that ToDictionary is not available through the standard Reflection library I'm familiar with.

Note: VB is even more verbose:

Dim d_filt = d_in.Where(Function(p) p.value > 2).ToDictionary(Function(p) p.Key, Function(p) p.Value)




Aucun commentaire:

Enregistrer un commentaire