How to set ExpandoObject's dictionary as case insensitive?
given the code below
dynamic e = new ExpandoObject();
var d = e as IDictionary<string, object>;
for (int i = 0; i < rdr.FieldCount; i++)
d.Add(rdr.GetName(i), DBNull.Value.Equals(rdr[i]) ? null : rdr[i]);
Is开发者_StackOverflow there a way to make it case insensitive so given the field name employee_name
e.Employee_name works just as well as e.employee_name
there doesn't seem to be an obvious way, perhaps a hack ?
I've been using this “Flexpando” class (for flexible expando) which is case-insensitive.
It's similar to Darin's MassiveExpando answer in that it gives you dictionary support, but by exposing this as a field it saves having to implement 15 or so members for IDictionary.
public class Flexpando : DynamicObject {
public Dictionary<string, object> Dictionary
= new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
public override bool TrySetMember(SetMemberBinder binder, object value) {
Dictionary[binder.Name] = value;
return true;
}
public override bool TryGetMember(GetMemberBinder binder, out object result) {
return Dictionary.TryGetValue(binder.Name, out result);
}
}
You may checkout Massive's implementation of a MassiveExpando
which is case insensitive dynamic object.
More as a curiosity than as a solution:
dynamic e = new ExpandoObject();
var value = 1;
var key = "Key";
var resul1 = RuntimeOps.ExpandoTrySetValue(
e,
null,
-1,
value,
key,
true); // The last parameter is ignoreCase
object value2;
var result2 = RuntimeOps.ExpandoTryGetValue(
e,
null,
-1,
key.ToLowerInvariant(),
true,
out value2); // The last parameter is ignoreCase
RuntimeOps.ExpandoTryGetValue/ExpandoTrySetValue
use internal methods of ExpandoObject
that can control the case sensitivity. The null, -1,
parameters are taken from the values used internally by ExpandoObject
(RuntimeOps
calls directly the internal methods of ExpandoObject
)
Remember that those methods are This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.
Another solution is to create a ExpandoObject
-like class by deriving from System.Dynamic.DynamicObject
and overriding TryGetValue
and TrySetValue
.
public static class IDictionaryExtensionMethods
{
public static void AddCaseInsensitive(this IDictionary dictionary, string key, object value)
{
dictionary.Add(key.ToUpper(), value);
}
public static object Get(this IDictionary dictionary, string key)
{
return dictionary[key.ToUpper()];
}
}
精彩评论