将变量分配给LINQ结果

时间:2020-10-21 19:14:10

标签: 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{
string SomeString {get; set;}
}

ObservableCollection<SomeClass> someCollection;

void foo(SomeClass foo2, string y){

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

}

但这似乎不是一种优雅的方法。 有正确的方法吗?

2 个答案:

答案 0 :(得分:0)

我建议创建一些扩展方法以扩展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;
    }
}

然后您可以在foo中使用它们:

void foo(SomeClass foo2, string y) {
    someCollection.SetFirstItem(x => x.SomeString == y, foo2);
}

答案 1 :(得分:-2)

左侧仍然不是变量。

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

ObservableCollection<SomeClass> someCollection;

void foo(string y){

var foo2 = someCollection[someCollection.IndexOf(someCollection.First(x => x.SomeString == y))] ;

}