4

以下の特定のシナリオで、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; }
    }
}

事前にご協力いただきありがとうございます。

4

2 に答える 2

6

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;

Note that neither solution is thread safe.


An ad hoc LINQ solution - you see, you should not use it because the whole array will be replaced with a new one.

this.Properties = Enumerable.Union(
   this.Properties.Where(p => p.Name != name),
   Enumerable.Repeat(value, 1)).
   ToArray();
于 2009-04-14T23:55:58.523 に答える
0

[注: この回答は質問の誤解によるものです - この回答のコメントを参照してください。どうやら、私は少し密集しています :(] あなたの「プロパティ」はクラスですか、それとも構造体ですか?

このテストは私に合格します:

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);
}

getter がデータ型 .Value ではなく「Property」を返すのはなぜなのか不思議に思う必要がありますが、私とは異なる結果が表示される理由はまだ気になります。

于 2009-04-15T00:23:32.717 に答える