을 반환하는 메서드가 IEnumerable<KeyValuePair<string, ArrayList>>
있지만 일부 호출자는 메서드의 결과를 사전으로 요구합니다. 어떻게 변환 할 수 있습니다 IEnumerable<KeyValuePair<string, ArrayList>>
에 Dictionary<string, ArrayList>
내가 사용할 수 있도록 TryGetValue
?
방법:
public IEnumerable<KeyValuePair<string, ArrayList>> GetComponents()
{
// ...
yield return new KeyValuePair<string, ArrayList>(t.Name, controlInformation);
}
방문객:
Dictionary<string, ArrayList> actual = target.GetComponents();
actual.ContainsKey("something");
답변
.NET 3.5 또는 .NET 4를 사용하는 경우 LINQ를 사용하여 사전을 쉽게 만들 수 있습니다.
Dictionary<string, ArrayList> result = target.GetComponents()
.ToDictionary(x => x.Key, x => x.Value);
와 같은 것은 IEnumerable<T1, T2>
없지만 a KeyValuePair<TKey, TValue>
는 괜찮습니다.