我試圖使用動態linq查詢從對象集合(Linq到Object)檢索IEnumerable <T>,每個對象都在該集合具有一個內部集合,其中包含另一組存儲數據的對象,這些值可通過外部集合中的索引器訪問Dynamic Linq - 對包含「dynamic」類型的成員執行查詢
當您使用強類型對象時,動態linq查詢將按預期返回過濾集但我的對象將數據存儲在動態類型的成員中,請參閱下面的示例:
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"]);
}
當我運行上面的例子,我得到:操作「==」與操作數類型的「對象」不兼容和「的Int32」
是動態成員動態LINQ查詢不兼容?或者是有處理動態
與會員處理正當評估時的另一種構建表達方式非常感謝您的幫助。
那他們不是真的'兼容'嗎? – 2012-01-12 02:38:43
謝謝,當我們事先知道該值的運行時類型時,該解決方案工作正常,但如何以編程方式構建查詢時,我們不會真正知道如何在事先手動轉換值。有沒有其他方式可以建立一個表達式? – Darsegura 2012-01-12 03:33:45
@ M.Babcock:取決於你對'兼容'的定義。 – afrischke 2012-01-12 10:38:34