Are dynamic members incompatible with Linq dynamic queries ?, or is there another way to build expressions that will be evaluated correctly when working with elements of type Dynamic ?
Both can work together. Just do the conversion to Int32 before doing the comparison as follows:
IEnumerable<DataItem> result = repository.AsQueryable<DataItem>().Where("Int32(it[\"Age\"]) == 30");
Edit 1: Having said that, the use of dynamic binding in connection with Linq is generally limited, since dynamic operations are not allowed in expression trees. Consider the following Linq-To-Objects query:
IEnumerable<DataItem> result = repository.AsQueryable(). Where(d => d["Age"] == 30);
This piece of code will not compile for the above reason.
Edit 2: In your case (and in combination with Dynamic Linq), there are several ways to hack yourself around the issues mentioned in Edit 1 and in the original question. For example:
// Variant 1: Using strings all the way public void DynamicQueryExample(string property, dynamic val) { List<DataItem> repository = new List<DataItem>(){ new DataItem() { new Data("Name", "Mike"), new Data("Age", 25), new Data("BirthDate", new DateTime(1987, 1, 5)) }, new DataItem() { new Data("Name", "Steve"), new Data("Age", 30), new Data("BirthDate", new DateTime(1982, 1, 10)) } }; // Use string comparison all the time string predicate = "it[\"{0}\"].ToString() == \"{1}\""; predicate = String.Format(whereClause , property, val.ToString()); var result = repository.AsQueryable<DataItem>().Where(predicate); if (result.Count() == 1) Console.WriteLine(result.Single()["Name"]); } Program p = new Program(); p.DynamicQueryExample("Age", 30); // Prints "Steve" p.DynamicQueryExample("BirthDate", new DateTime(1982, 1, 10)); // Prints "Steve" p.DynamicQueryExample("Name", "Mike"); // Prints "Steve" (nah, just joking...)
or
// Variant 2: Detecting the type at runtime. public void DynamicQueryExample(string property, string val) { List<DataItem> repository = new List<DataItem>(){ new DataItem() { new Data("Name", "Mike"), new Data("Age", 25), new Data("BirthDate", new DateTime(1987, 1, 5)) }, new DataItem() { new Data("Name", "Steve"), new Data("Age", 30), new Data("BirthDate", new DateTime(1982, 1, 10)) } }; string whereClause = "{0}(it[\"{1}\"]) == {2}"; // Discover the type at runtime (and convert accordingly) Type type = repository.First()[property].GetType(); string stype = type.ToString(); stype = stype.Substring(stype.LastIndexOf('.') + 1); if (type.Equals(typeof(string))) { // Need to surround formatting directive with "" whereClause = whereClause.Replace("{2}", "\"{2}\""); } string predicate = String.Format(whereClause, stype, property, val); var result = repository.AsQueryable<DataItem>().Where(predicate); if (result.Count() == 1) Console.WriteLine(result.Single()["Name"]); } var p = new Program(); p.DynamicQueryExample("Age", "30"); p.DynamicQueryExample("BirthDate", "DateTime(1982, 1, 10)"); p.DynamicQueryExample("Name", "Mike");