我有一個對象的ICollection:
private ObservableCollection<ViewItem> items;
viewItems沒有屬性。數據將通過帶有
public object this[int index] {
get{ .... }
set {....}
}
我有一個通用的過濾類。具有屬性的linq可以正常工作。我使用(僅重要代碼):
Queryable = CreateQueryable((IEnumerable<object>)mItemsSource.SourceCollection, ItemType);
mQuery = Queryable.Where(filterString).Cast<object>();
ilteredCollection = mQuery.ToList();
與:
private static IQueryable CreateQueryable(IEnumerable<object> collection, Type itemType)
{
if (itemType == null) return null;
var queryableList = collection.AsQueryable();
return queryableList.Provider.CreateQuery(
Expression.Call(
typeof(Queryable), "Cast",
new Type[] { itemType },
queryableList.Expression));
}
因此,我可以使用以下過濾字符串: Id>10
或Name="abc"
,其中Id
和Name
是屬性名稱。
但是我在另一個只能通過索引訪問的集合中也有對象。所以我有一個where字符串,像:
[0]>10 or [1]="abc"
我沒有找到任何解決方案。我唯一能找到的提示是使用:
new(it([idx] as Type)
其中idx
是元素索引,而Type
是此元素的類型
例如
[0]>10 --> new(it[0] as object)>10
但是比我得到的錯誤:
{“運算符'='與操作數類型'DynamicClass1'和'Int32'不兼容”}
在我的過濾器中使用一個字符串,例如:
new(it[0] as object)>"10"
比錯誤是:
{“運算符'='與操作數類型'DynamicClass1'和'string'不兼容”}}
所以-我該如何解決這個問題。因為這是一般的Filterclass,我也不知道類型 。因此,在as語句中,我只能使用object或類似的東西。
我希望任何人都能幫助我。也許C#4.0的動態關鍵字會有所幫助?順便說一句,一種解決方法是在每個類中使用索引器添加一個包裝器,但這將是很多愚蠢的工作。那是真正的程序員不喜歡的;)。我確定有解決方案!
您對new
關鍵字的使用是錯誤的。它不投對象(也沒有as
)。
關鍵字new
用於創建具有指定屬性的匿名類的新對象。因此, new(it[idx] as Type)
將創建屬性Type
為值it[idx]
新對象。它等效於C#: new { Type = this[idx] }
。
正如我已經在Dynamic linq中指出的那樣:有沒有一種通過索引訪問對像數據的方法? ,則需要按以下方式進行轉換:偽查詢[0] > 10
Int32(it[0]) > 10
[0] > 10
。
振作起來 !!
首先-如何訪問當前實例?
當使用單個未命名參數解析lambda表達式時,未命名參數的成員會自動在表達式字符串的作用域中,並且可以使用關鍵字it整體引用未命名參數給出的當前實例。例如,
customer.Where(“ Country = @ 0”,國家/地區);
相當於
customer.Where(“ it.Country = @ 0”,國家/地區);
根據上面的解釋,我們現在可以訪問indexer屬性[@ 0],其中@ 0是要傳遞的索引值,如下所述。
//考慮下課
public class Product
{
private NameValueCollection collection = new NameValueCollection();
public string Company { get; set; }
public string Distributor { get; set; }
public int ID { get; set; }
...
public string this[string index]
{
get { return collection[index]; }
set { if(!string.IsNullOrEmpty(value)) collection[index]=value; }
}
}
//主要代碼
List<Product> list = new List<Product>();
Product product = new Product() { Company = "Nestle", Distributor = "xyz", ID = 1 };
product["Name"] = "Maggi";
list.Add(product);
var filteredList = list.AsQueryable().Where("it[@0]=@1", "Name", "Maggi"); //Accessing the current item by indexer property
foreach (Product productItem in filteredList)
{
Console.WriteLine(productItem.Company);
}
希望這對您有幫助! :)