C# 将代码优化为linq表达式
我有一个可观察的集合,我想从中删除一个元素。我已经尝试过使用linq.Where语法,但是我一直在使用强制转换C# 将代码优化为linq表达式,c#,linq,C#,Linq,我有一个可观察的集合,我想从中删除一个元素。我已经尝试过使用linq.Where语法,但是我一直在使用强制转换 public class Atc { public string Code { get; set; } public string Description { get; set; } public string ParentDescriptions { get; set; } } 我已经定义了可观察的药物集合 public ObservableCollecti
public class Atc
{
public string Code { get; set; }
public string Description { get; set; }
public string ParentDescriptions { get; set; }
}
我已经定义了可观察的药物集合
public ObservableCollection<Atc> MedicinesObservableCollection
public observeablecollection MedicinesObservableCollection
我有一种方法可以从集合中筛选出有效的项目:
private void RemoveMedicineListItem(string code)
{
var filteredCollection = new ObservableCollection<Atc>();
foreach (var item in MedicinesObservableCollection)
{
if (item.Code != code)
{
filteredCollection.Add(item);
}
}
MedicinesObservableCollection = filteredCollection;
}
private void RemoveMedicineListItem(字符串代码)
{
var filteredCollection=新的ObservableCollection();
foreach(MedicinesObservableCollection中的var项目)
{
如果(item.Code!=代码)
{
filteredCollection.Add(项);
}
}
MedicinesObservableCollection=filteredCollection;
}
我试过:
(ObservableCollection<Atc>)MedicinesObservableCollection.Where(x => x.Code != code);
(ObservableCollection)MedicineServableCollection。其中(x=>x.code!=code);
但这会得到一个运行时异常
System.InvalidCastException:“无法将类型为'WhereEnumerableTerator1[Atc]'的对象强制转换为类型为'System.Collections.ObjectModel.ObservableCollection1[Atc]'。”
我知道这与linq可枚举性有关,但我的深度不够。您不能将WhereIterator
(您的Where
-子句实际返回的实例强制转换为observeCollection)
。返回的实例只实现了IEnumerable
,这就是您可以迭代它的原因。然而,它与任何列表没有任何共同之处,尤其是与可观察列表没有任何共同之处
但是,您可以根据返回的值创建一个新值:
var result = new ObservableCollection(MedicinesObservableCollection.Where(x => x.Code != code));
Linq不会返回与输入类型相同的集合。看见因此,您对ObservableCollection的强制转换:
var items=newobserveCollection(MedicinesObservableCollection.Where(x=>x.code!=code));
所有答案都是正确的,但使用ObservableCollection
时,最好对同一对象执行删除操作,而不是创建新列表
MedicinesObservableCollection.Remove(MedicinesObservableCollection.FirstOrDefault(x => x.Code == code));
这是因为重新创建集合可能会强制重新呈现列表中的所有项,这样,同一集合中只会删除一项。使用构造函数:
MedicinesObservableCollection.Remove(MedicinesObservableCollection.FirstOrDefault(x => x.Code == code));