[英]IQueryable remove from the collection, best way?
IQueryable<SomeType> collection = GetCollection();
foreach (var c in collection)
{
//do some complex checking that can't be embedded in a query
//based on results from prev line we want to discard the 'c' object
}
//here I only want the results of collection - the discarded objects
因此,使用該簡單的代碼,獲得結果的最佳方法是什么。 我應該在foreach之前創建一個List並插入要保留的對象,還是可以通過其他方法更好地進行此類操作。
我知道還有其他類似主題的文章,但是我只是覺得自己沒有得到我需要的東西。
編輯我嘗試了這個
var collection = GetCollection().Where(s =>
{
if (s.property == 1)
{
int num= Number(s);
double avg = Avg(s.x);
if (num > avg)
return true;
else
return false;
}
else return false;
});
我嘗試了此操作,但在編譯時得到了“帶有語句主體的lambda表達式無法轉換為表達式樹”。 我做錯了嗎?
//do some complex checking that can't be embedded in a query
我不明白 您可以傳遞一個委托,該委托可以指向一個非常復雜的函數(圖靈完成),該函數檢查是否應丟棄它:
var result = GetCollection().AsEnumerable().Where(c => {
// ...
// process "c"
// return true if you want it in the collection
});
如果需要,可以在另一個函數中對其進行重構:
var result = GetCollection.Where(FunctionThatChecksToDiscardOrNot);
如果將其包裝到另一個方法中,則可以使用yield return然后對返回的集合進行迭代,如下所示:
public IEnumerable<SomeType> FindResults(IQueryable<SomeType> collection) {
foreach (var c in collection)
{
if (doComplicatedQuery(c)) {
yield return c;
}
}
}
// elsewhere
foreach (var goodItem in FindResults(GetCollection())) {
// do stuff.
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.