your programing

사전 값을 배열로 변환

lovepro 2020. 10. 14. 08:16
반응형

사전 값을 배열로 변환


사전의 값 목록을 배열로 바꾸는 가장 효율적인 방법은 무엇입니까?

나는이있는 경우 예를 들어, DictionaryKey이다 StringValue이다 Foo, 나는 싶어Foo[]

VS 2005, C # 2.0을 사용하고 있습니다.


// dict is Dictionary<string, Foo>

Foo[] foos = new Foo[dict.Count];
dict.Values.CopyTo(foos, 0);

// or in C# 3.0:
var foos = dict.Values.ToArray();

목록에 저장하십시오. 더 쉽습니다.

List<Foo> arr = new List<Foo>(dict.Values);

물론 특별히 배열로 원한다면;

Foo[] arr = (new List<Foo>(dict.Values)).ToArray();

값에는 ToArray () 함수가 있습니다.

Foo[] arr = new Foo[dict.Count];    
dict.Values.CopyTo(arr, 0);

그러나 나는 그것이 효율적이라고 생각하지 않습니다 (실제로 시도하지는 않았지만 모든 값을 배열에 복사한다고 생각합니다). 정말 어레이가 필요합니까? 그렇지 않은 경우 IEnumerable을 전달하려고합니다.

IEnumerable<Foo> foos = dict.Values;

linq를 사용하려면 다음을 시도해보세요.

Dictionary<string, object> dict = new Dictionary<string, object>();
var arr = dict.Select(z => z.Value).ToArray();

어느 것이 더 빠르거나 더 좋은지 모르겠습니다. 둘 다 나를 위해 일합니다.


요즘에는 LINQ를 사용할 수있게되면 사전 키와 해당 값을 단일 문자열로 변환 할 수 있습니다.

다음 코드를 사용할 수 있습니다.

// convert the dictionary to an array of strings
string[] strArray = dict.Select(x => ("Key: " + x.Key + ", Value: " + x.Value)).ToArray();

// convert a string array to a single string
string result = String.Join(", ", strArray);

참고 URL : https://stackoverflow.com/questions/197059/convert-dictionary-values-into-array

반응형