【问题标题】:Using LINQ to delete an element from a ObservableCollection Source [duplicate]使用 LINQ 从 ObservableCollection 源中删除元素 [重复]
【发布时间】:2012-07-16 08:17:13
【问题描述】:

实际上,它更接近于:
RemoveAll for ObservableCollections?

罢工>

可能重复:
using LINQ to remove objects within a List<T>

这是我正在使用的代码,但它的可读性不是很好。我可以使用 LINQ 缩短下面的代码,同时仍然具有相同的功能吗?

int index = 0;
int pos = 0;

foreach (var x in HomeViewModel.RecentPatients)
{
   if (x.PID == p.PID)
       pos = index;
   else
       index++;

}

HomeViewModel.RecentPatients.RemoveAt(pos); 

【问题讨论】:

  • @Adam Houldsworth 来自 List,我指定了 ObservableCollection Source。
  • 这与您之前的问题有何不同? stackoverflow.com/q/11498056/201088
  • @SupaOden 我注意到了,但我无法编辑接近投票。只有在关闭时才投票重新开放。道歉。
  • 说起来更像是stackoverflow.com/questions/5118513/…的复制品
  • 最好的方法是 HomeViewModel.RecentPatients.Where(p => ... ).ToList().All(i => HomeViewModel.RecentPatients.Remove(i));

标签: c# linq foreach


【解决方案1】:

对重复的关闭混淆表示歉意。这个问题和标记的答案将使您拥有从可观察集合中删除的扩展方法支持:

RemoveAll for ObservableCollections?

它不会支持from x in y 语法,但它会让你这样做:

var c = new ObservableCollection<SelectableItem>();
c.Remove(x => x.IsSelected);

但是,通过检查 x.PID == p.PID 和有关您的其他问题的注释...如果实际上您想删除两个列表中的项目,这可能不是最佳选择。

Except 扩展方法将生成一个项目的可枚举项,这些项目排除作为参数提供的可枚举项中的项目,在您的情况下是第二个列表。此方法不会改变现有的可枚举,就像大多数操作一样,它会返回一个新的,因此您需要将其设置为新的 ObservableCollection

【讨论】:

    【解决方案2】:

    你可以试试这个。

    var toRemove = HomeViewModel.RecentPatients.Where(x=>x.PID == pid).ToList();
    foreach (var item in toRemove)
        HomeViewModel.RecentPatients.Remove(item);
    

    【讨论】:

    • 使用此代码,您应该尝试仅从集合中删除一行。不仅如此,我们还会得到以下异常“Collection was modified; enumeration operation may not execute”。因此,在第一次执行后打破 for each 循环或复制到新的 collection.foreach (var item in toRemove) { HomeViewModel.RecentPatients.Remove(item);休息;}
    • 即使里面有 ToList()?
    猜你喜欢
    • 1970-01-01
    • 2021-07-27
    • 2012-11-09
    • 2010-10-25
    • 1970-01-01
    • 1970-01-01
    • 2013-05-19
    • 2013-07-12
    • 2014-01-19
    相关资源
    最近更新 更多