C# 将变量指定给LINQ结果

C# 将变量指定给LINQ结果,c#,linq,variables,variable-assignment,C#,Linq,Variables,Variable Assignment,我得到以下错误 分配的左侧必须是变量、属性或索引器 在此代码中: class SomeClass{ string SomeString {get; set;} } ObservableCollection<SomeClass> someCollection; void foo(SomeClass foo2, string y){ someCollection.First(x => x.SomeString == y) = foo2; } class-SomeClass

我得到以下错误 分配的左侧必须是变量、属性或索引器 在此代码中:

class SomeClass{
string SomeString {get; set;}
}

ObservableCollection<SomeClass> someCollection;

void foo(SomeClass foo2, string y){

someCollection.First(x => x.SomeString == y) = foo2;

}
class-SomeClass{
字符串SomeString{get;set;}
}
可观察收集;
void foo(SomeClass foo2,字符串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;

}
class-SomeClass{
字符串SomeString{get;set;}
}
可观察收集;
void foo(SomeClass foo2,字符串y){
someCollection[someCollection.IndexOf(someCollection.First(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))] ;

}
class-SomeClass{
字符串SomeString{get;set;}
}
可观察收集;
void foo(字符串y){
var foo2=someCollection[someCollection.IndexOf(someCollection.First(x=>x.SomeString==y));
}

我建议为您的新功能创建一些扩展方法来扩展
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, Func<T, bool> predFn, T newItem) {
        var index = aCollection.IndexOf(predFn);
        if (index != -1)
            aCollection[index] = newItem;
    }
}

标题应该是:替换ObservableCollection中的项,因为这是您试图以“优雅的方式”实现的。
someCollection[…]
当然是一个可修改的左值。
void foo(SomeClass foo2, string y) {
    someCollection.SetFirstItem(x => x.SomeString == y, foo2);
}