[英]LinqToSQL removing specific child nodes from a list of parent nodes
我有一個ObservableCollection
的食譜,每個食譜都有一個ObservableCollection
的成分。 假設我想使用 Linq 從所有食譜中修改或移除某種成分(例如,從所有食譜中移除花生)。 我試過做這樣的事情:
foreach(Recipe r in myObservableRecipes)
{
r.ObservableIngredients.RemoveAll(i => i.Type == PEANUTS);
}
但這不起作用,因為成分列表是 ObservableCollection 而RemoveAll
是List<T>
方法。 如果我添加ToList().RemoveAll()
它實際上並沒有從集合中刪除它們,而是從集合的副本中刪除它們。 我找不到似乎有效的 Remove Where 組合,因為 Where 返回一個沒有Remove
調用的IEnumerable
。
我正在做的是:
foreach(Recipe r in myObservableRecipes)
{
var ingToRemove = new HashSet<Ingredient>(r.myObservableIngredients.Where(i => i.Type == PEANUTS));
foreach (Ingredient i in r.myObservableIngredients.ToList())
{
if(ingToRemove.Contains(i)) r.myObservableIngredients.Remove(i);
}
RaisePropertyChangedEvent("myObservableIngredients");
}
這可行,但在實體集和可觀察 collections 的交集處似乎很笨拙。 我實際上也在同一個循環內從實體集 ( DeleteOnSubmit
) 中刪除相同的實體,然后調用提交更改。 這是將LinqToSQL
實體與 WPF 和ObservableCollections/CollectionViewSource
范例一起使用的設計意圖嗎?
使用ObservableCollection<T>
的全部意義在於,您可以從中添加或刪除項目並更新 UI,而無需創建任何額外的 collections。
只需使用嵌套的普通for
循環:
for (int i = myObservableRecipes.Count - 1; i >= 0; --i)
{
Recipe r = myObservableRecipes[i];
for (int j = r.myObservableIngredients.Count - 1; j >= 0; j--)
{
Ingredient ing = r.myObservableIngredients[j];
if (ing.Type == PEANUTS)
r.myObservableIngredients.RemoveAt(j);
}
//remove recipes without any remaining ingredients
if (r.myObservableIngredients.Count == 0)
myObservableRecipes.RemoveAt(i);
}
與使用 LINQ 並創建額外的 collections 多次迭代同一集合相比,這並不“笨拙”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.