LINQ를 사용하여 수집 항목을 교체하십시오
-
09-09-2019 - |
문제
아래 의이 특정 시나리오에서 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를 사용하지 않으므로 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;
솔루션은 스레드 안전하지 않습니다.
Ad Hoc 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);
}
getter가 왜 데이터 유형 대신 '속성'을 반환하는지 궁금해해야하지만, 왜 내가 당신이 내가있는 것과 다른 결과를보고 있는지 여전히 궁금합니다.
제휴하지 않습니다 StackOverflow