I am trying to use a dynamic linq query to retrieve an IEnumerable<T> from an object collection (Linq to Object), each of the objects in the collection have an internal collection with another set of objects where the data is stored, these values are accessed through an indexer from the outer collection
The dynamic linq query returns the filtered set as expected when you are working with strongly typed objects but my object stores the data in a member of type dynamic, please see the example below:
public class Data
{
public Data(string name, dynamic value)
{
this.Name = name;
this.Value = value;
}
public string Name { get; set; }
public dynamic Value { get; set; }
}
public class DataItem : IEnumerable
{
private List<Data> _collection;
public DataItem()
{ _collection = new List<Data>(); }
public dynamic this[string name]
{
get
{
Data d;
if ((d = _collection.FirstOrDefault(i => i.Name == name)) == null)
return (null);
return (d.Value);
}
}
public void Add(Data data)
{ _collection.Add(data); }
public IEnumerator GetEnumerator()
{
return _collection.GetEnumerator();
}
}
public class Program
{
public void Example()
{
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))
}
};
IEnumerable<DataItem> result = repository.AsQueryable<DataItem>().Where("it[\"Age\"] == 30");
if (result.Count() == 1)
Console.WriteLine(result.Single()["Name"]);
}
When I run the above example I get: Operator '==' incompatible with operand types 'Object' and 'Int32'
Are dynamic members incompatible with Dynamic Linq queries?, or is there another way of constructing expressions that would evaluate properly when dealing with members of type dynamic
Thanks a lot for your help.