如何解决将变量分配给LINQ结果
我收到以下错误 “组合的左侧必须是变量,属性或索引器” 在此代码中:
class SomeClass{
string SomeString {get; set;}
}
ObservableCollection<SomeClass> someCollection;
void foo(SomeClass foo2,string y){
someCollection.First(x => x.someString == y) = foo2;
}
我了解为什么会发生此错误,因此我编写了以下代码来解决该问题:
class SomeClass{
string SomeString {get; set;}
}
ObservableCollection<SomeClass> someCollection;
void foo(SomeClass foo2,string y){
someCollection[someCollection.IndexOf(someCollection.First(x => x.someString == y))] = foo2;
}
解决方法
我建议创建一些扩展方法以扩展ObservableCollection
以获得新功能:
public static class ObservableCollectionExt {
public static int IndexOf<T>(this ObservableCollection<T> aCollection,Func<T,bool> predFn) => aCollection.Select((c,n) => new { c,n }).FirstOrDefault(cn => predFn(cn.c))?.n ?? -1;
public static void SetFirstItem<T>(this ObservableCollection<T> aCollection,bool> predFn,T newItem) {
var index = aCollection.IndexOf(predFn);
if (index != -1)
aCollection[index] = newItem;
}
}
然后您可以在foo
中使用它们:
void foo(SomeClass foo2,string y) {
someCollection.SetFirstItem(x => x.SomeString == y,foo2);
}
,
左侧仍然不是变量。
class SomeClass{
string SomeString {get; set;}
}
ObservableCollection<SomeClass> someCollection;
void foo(string y){
var foo2 = someCollection[someCollection.IndexOf(someCollection.First(x => x.SomeString == y))] ;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。