Pregunta

¿Cómo buscar y reemplazar una propiedad utilizando LINQ en este escenario específico a continuación:

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

Gracias por su ayuda de antemano.

¿Fue útil?

Solución

No utilizar LINQ porque no va a mejorar el código LINQ porque está diseñado para consultar colectivo y no para modificarlos. Sugiero lo siguiente.

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

¿Por qué Array.Sort () y Array.indexOf () métodos estáticos?

Además I sugieren no utilizar una matriz. Considere el uso de IDictionary<String, Property>. Esto simplifica el código a la siguiente.

this.Properties[name] = value;

Tenga en cuenta que ninguna de las soluciones es hilo de seguridad.


Una solución ad hoc LINQ - que se ve, no se debe utilizar porque todo el conjunto será reemplazado por uno nuevo

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

Otros consejos

[Nota: esta respuesta se debió a una mala interpretación de la pregunta - ver los comentarios de esta respuesta. Al parecer, estoy un poco densa :(] Es el 'Propiedad' una clase o una estructura?

Esta prueba pasa por mí:

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

Tengo que preguntarse por qué el comprador devuelve una 'propiedad' en lugar de cualquier tipo de datos .Value, pero todavía estoy curioso por qué se está viendo un resultado diferente de lo que soy.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top