【问题标题】:Assign a variable to a LINQ result将变量分配给 LINQ 结果
【发布时间】:2021-02-04 18:16:51
【问题描述】:

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

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 中的项目,因为这是您尝试以“优雅的方式”实现的目标。

标签: c# linq variables variable-assignment


【解决方案1】:

我建议为您的新功能创建一些扩展方法来扩展 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);
}

【讨论】:

    【解决方案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))] ;
    
    }
    

    【讨论】:

    • someCollection[...] 肯定是一个可修改的左值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-02
    • 2020-12-01
    • 2011-08-27
    • 1970-01-01
    相关资源
    最近更新 更多