title: Filter a Generic list using LINQ using a PropertyName as a string literal - Using dynamics
body: <p>I am wondering whether this method can be done better. I need to filter a Generic list on a member name which is passed in as string. My thinking was to convert the generic list to a dynamic list and then cast the expandoObject to a Dictionary and check for the existence of the member name. Finally, convert the dynamic list back to generic list by using JsonSerializer. What are your ideas for a better implementation? Reflection? Dynamic LINQ (Scott Guthrie did some work back in 2008)? Expression Trees?</p>
  
  <pre><code>        public static IEnumerable&lt;T&gt; FilterListByStringPropertyName&lt;T&gt;(this IEnumerable&lt;T&gt; genericList, int? enumId, string enumFieldName)
      {
          if (string.IsNullOrEmpty(enumFieldName))
          {
              throw new NullReferenceException("FilterByEnum: enumFieldName cannot be empty");
          }
  
          if (enumId == null)
          {
              //skip method as no filtering needed
              return genericList;
          }
  
          if (genericList.Count() == 0)
          {
              return genericList;
          }
  
          List&lt;T&gt; @return = new List&lt;T&gt;();
          List&lt;dynamic&gt; dynamicList = new List&lt;dynamic&gt;();
  
          //fill the dynamic list from generic list
          foreach (var genericItem in genericList)
              dynamicList.Add(genericItem.ToDynamic());
  
          var first = dynamicList.FirstOrDefault();
  
          //initialise filteredDynamicList
          IEnumerable&lt;dynamic&gt; filteredDynamicList = dynamicList;
  
          if (enumId != null)
          {
              //ExpandoObject implements IDictionary&lt;string, object&gt;, so cast as that to check what the fields are
              if (!((IDictionary&lt;string, object&gt;)first).ContainsKey(enumFieldName))
              {
                  throw new KeyNotFoundException(string.Format("{0} is not a member of {1}", enumFieldName, genericList.GetType().GetGenericArguments()[0]));
              }
  
              //filter by the AddressStatus enum (as int)
              filteredDynamicList = dynamicList.Where(a =&gt; (int)((IDictionary&lt;string, object&gt;)a)[enumFieldName] == enumId.Value);
          }
  
          //convert from dynamic back to to generic
          var json = Newtonsoft.Json.JsonConvert.SerializeObject(filteredDynamicList);
          @return = Newtonsoft.Json.JsonConvert.DeserializeObject&lt;List&lt;T&gt;&gt;(json);
  
          return @return;
      }
  </code></pre>