두 목록을 C #의 사전에 매핑
같은 크기의 두IEnumerable
s 가 주어지면 Linq를 사용하여 어떻게 변환 할 수 Dictionary
있습니까?
IEnumerable<string> keys = new List<string>() { "A", "B", "C" };
IEnumerable<string> values = new List<string>() { "Val A", "Val B", "Val C" };
var dictionary = /* Linq ? */;
예상되는 출력은 다음과 같습니다.
A: Val A
B: Val B
C: Val C
그것을 달성하는 간단한 방법이 있는지 궁금합니다.
성능에 대해 걱정해야합니까? 큰 컬렉션이 있으면 어떻게하나요?
더 쉬운 방법이 없다면 현재 다음과 같이하고 있습니다.
IEnumerable
요소와 인덱스 번호를 제공하는 반복되는 Extension 메서드가 있습니다.
public static class Ext
{
public static void Each<T>(this IEnumerable els, Action<T, int> a)
{
int i = 0;
foreach (T e in els)
{
a(e, i++);
}
}
}
그리고 Enumerable 중 하나를 반복하고 인덱스를 사용하여 다른 Enumerable에서 동등한 요소를 검색하는 메서드가 있습니다.
public static Dictionary<TKey, TValue> Merge<TKey, TValue>(IEnumerable<TKey> keys, IEnumerable<TValue> values)
{
var dic = new Dictionary<TKey, TValue>();
keys.Each<TKey>((x, i) =>
{
dic.Add(x, values.ElementAt(i));
});
return dic;
}
그런 다음 다음과 같이 사용합니다.
IEnumerable<string> keys = new List<string>() { "A", "B", "C" };
IEnumerable<string> values = new List<string>() { "Val A", "Val B", "Val C" };
var dic = Util.Merge(keys, values);
출력은 정확합니다.
A: Val A
B: Val B
C: Val C
.NET 4.0 (또는 Rx의 System.Interactive 3.5 버전)에서는 다음을 사용할 수 있습니다 Zip()
.
var dic = keys.Zip(values, (k, v) => new { k, v })
.ToDictionary(x => x.k, x => x.v);
Or based on your idea, LINQ includes an overload of Select()
that provides the index. Combined with the fact that values
supports access by index, one could do the following:
var dic = keys.Select((k, i) => new { k, v = values[i] })
.ToDictionary(x => x.k, x => x.v);
(If values
is kept as List<string>
, that is...)
I like this approach:
var dict =
Enumerable.Range(0, keys.Length).ToDictionary(i => keys[i], i => values[i]);
If you use MoreLINQ, you can also utilize it's ToDictionary extension method on previously created KeyValuePair
s:
var dict = Enumerable
.Zip(keys, values, (key, value) => KeyValuePair.Create(key, value))
.ToDictionary();
It also should be noted that using Zip
extension method is safe against input collections of different lengths.
참고URL : https://stackoverflow.com/questions/4038978/map-two-lists-into-a-dictionary-in-c-sharp
'developer tip' 카테고리의 다른 글
numpy.matrix 또는 배열을 scipy 희소 행렬로 변환하는 방법 (0) | 2020.11.24 |
---|---|
PDO PHP에서 쿼리 오류를 보는 방법 (0) | 2020.11.24 |
$ .ajax (serialize () + extra data)를 통해 데이터를 추가하는 방법 (0) | 2020.11.23 |
Visual Studio 2010은 소스 파일을 변경 한 후 오류없이 빌드가 실패했다고 말합니다. (0) | 2020.11.23 |
MVC : 문자열을 JSON으로 반환하는 방법 (0) | 2020.11.23 |