如何找到并在下面这种特定情况下替换使用LINQ属性:

public interface IPropertyBag { }
public class PropertyBag : IPropertyBag
{
    public Property[] Properties { get; set; }

    public Property this[string name]
    {
        get { return Properties.Where((e) => e.Name == name).Single(); }
        //TODO: Just copying values... Find out how to find the index and replace the value 
        set { Properties.Where((e) => e.Name == name).Single().Value = value.Value; }
    }
}

感谢提前帮忙。

有帮助吗?

解决方案

不要使用LINQ,因为,因为LINQ是设计用来查询集合而不是对其进行修改也不会提高代码。我建议以下内容。

// Just realized that Array.IndexOf() is a static method unlike
// List.IndexOf() that is an instance method.
Int32 index = Array.IndexOf(this.Properties, name);

if (index != -1)
{
   this.Properties[index] = value;
}
else
{
   throw new ArgumentOutOfRangeException();
}

为什么的Array.Sort()和Array.IndexOf ()方法的静态?

此外我建议不要使用数组。考虑使用IDictionary<String, Property>。这简化了代码下面的内容。

this.Properties[name] = value;

请注意,无论是溶液是线程安全的。


这是特设LINQ的解决方案 - 你看,你不应该使用它,因为整个阵列将用一个新的来代替

this.Properties = Enumerable.Union(
   this.Properties.Where(p => p.Name != name),
   Enumerable.Repeat(value, 1)).
   ToArray();

其他提示

[注:这个答案是由于问题的误解 - 看到这个答案的评论。很显然,我有点密集:(] 是你的“财产”类或结构?

此测试通过对我来说:

public class Property
{
    public string Name { get; set; }
    public string Value { get; set; }
}
public interface IPropertyBag { }
public class PropertyBag : IPropertyBag
{
    public Property[] Properties { get; set; }

    public Property this[string name]
    {
        get { return Properties.Where((e) => e.Name == name).Single(); }
        set { Properties.Where((e) => e.Name == name).Single().Value = value.Value; }
    }
}

[TestMethod]
public void TestMethod1()
{
    var pb = new PropertyBag() { Properties = new Property[] { new Property { Name = "X", Value = "Y" } } };
    Assert.AreEqual("Y", pb["X"].Value);
    pb["X"] = new Property { Name = "X", Value = "Z" };
    Assert.AreEqual("Z", pb["X"].Value);
}

我想知道为什么,吸气返回,而不是任何数据类型.value的“财产”,但我仍然好奇,为什么你看到一个不同的结果比我的东西。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top