Replace a collection item using Linq

Vyas Bharghava picture Vyas Bharghava · Apr 15, 2009 · Viewed 16.4k times · Source

How do I find and replace a property using Linq in this specific scenario below:

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

Thanks for helping out in advance.

Answer

Daniel Brückner picture Daniel Brückner · Apr 15, 2009

Do not use LINQ because it will not improve the code because LINQ is designed to query collection and not to modify them. I suggest the following.

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

Why are Array.Sort() and Array.IndexOf() methods static?

Further I suggest not to use an array. Consider using IDictionary<String, Property>. This simplifies the code to the following.

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