Vya*_*ava 4 c# linq linq-to-objects .net-3.0
在下面的特定方案中,如何使用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; }
}
}
Run Code Online (Sandbox Code Playgroud)
感谢您提前帮忙.
不要使用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();
}
Run Code Online (Sandbox Code Playgroud)
为什么Array.Sort()和Array.IndexOf()方法是静态的?
此外,我建议不要使用数组.考虑使用IDictionary<String, Property>.这简化了以下代码.
this.Properties[name] = value;
Run Code Online (Sandbox Code Playgroud)
请注意,这两种方法都不是线程安全
临时LINQ解决方案 - 您看,您不应该使用它,因为整个阵列将被替换为新阵列.
this.Properties = Enumerable.Union(
this.Properties.Where(p => p.Name != name),
Enumerable.Repeat(value, 1)).
ToArray();
Run Code Online (Sandbox Code Playgroud)