Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用LINQ从ObservableCollection源中删除元素_C#_Linq_Foreach - Fatal编程技术网

C# 使用LINQ从ObservableCollection源中删除元素

C# 使用LINQ从ObservableCollection源中删除元素,c#,linq,foreach,C#,Linq,Foreach,实际上,它与: 可能重复: 这是我正在使用的代码,但可读性不强。我可以使用LINQ来缩短下面的代码,同时仍然具有相同的功能吗 int index = 0; int pos = 0; foreach (var x in HomeViewModel.RecentPatients) { if (x.PID == p.PID) pos = index; else index++; } HomeViewModel.RecentPatients.Remo

实际上,它与:

可能重复:

这是我正在使用的代码,但可读性不强。我可以使用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); 

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

它不支持从x到y的
语法,但它允许您执行以下操作:

var c = new ObservableCollection<SelectableItem>();
c.Remove(x => x.IsSelected);
var c=新的ObservableCollection();
c、 移除(x=>x.IsSelected);
但是,通过检查
x.PID==p.PID
和关于其他问题的注释。。。如果事实上您想要删除两个列表中的项目,这可能不是最好的选择

扩展方法将生成一个可枚举项,其中排除作为参数提供的可枚举项中的项,在本例中为第二个列表。此方法不会改变现有的可枚举项,与大多数操作一样,它会返回一个新的可枚举项,因此您需要将其设置为一个新的
可观察集合

您可以尝试此方法

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

@Adam Houldsworth,这是一个列表,我指定了ObservableCollection源。这与您之前的问题有什么不同@我注意到了苏波登,但我无法修改接近票数的选票。只有在关闭时才投票重新打开。抱歉。这么说来,它更像是HomeViewModel.RecentPatients.Where(p=>…).ToList().All(i=>HomeViewModel.RecentPatients.Remove(i))的复制品;使用此代码,您应该尝试从集合中仅删除一行。除此之外,我们还将得到以下异常“Collection was modified;enumeration operation may not execute.”因此,在第一次执行后中断for each循环,或者复制到一个新的Collection.foreach(toRemove中的var item){HomeViewModel.RecentPatients.Remove(item);break;}即使其中有ToList()?