How to set ExpandoObject's dictionary as case insensitive?

﹥>﹥吖頭↗ 提交于 2020-01-23 06:26:27

问题


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 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 ?


回答1:


You may checkout Massive's implementation of a MassiveExpando which is case insensitive dynamic object.




回答2:


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);
    }
}



回答3:


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.




回答4:


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()];
   }
}




回答5:


Another solution is to create a ExpandoObject-like class by deriving from System.Dynamic.DynamicObject and overriding TryGetValue and TrySetValue.



来源:https://stackoverflow.com/questions/7760035/how-to-set-expandoobjects-dictionary-as-case-insensitive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!