簡體   English   中英

將C#字符串數組轉換為字典

[英]Convert a C# string array to a dictionary

是否有一種優雅的方式來轉換這個字符串數組:

string[] a = new[] {"name", "Fred", "colour", "green", "sport", "tennis"};

進入一個字典,使得數組的每兩個連續元素成為一個{key,value}字典對(我的意思是{“name” - >“Fred”,“color” - >“green”,“sport” - > “網球”})?

我可以通過循環輕松完成,但有更優雅的方式,也許使用LINQ?

var dict = a.Select((s, i) => new { s, i })
            .GroupBy(x => x.i / 2)
            .ToDictionary(g => g.First().s, g => g.Last().s);

因為它是一個數組,我會這樣做:

var result = Enumerable.Range(0,a.Length/2)
                       .ToDictionary(x => a[2 * x], x => a[2 * x + 1]);

這個怎么樣 ?

    var q = a.Zip(a.Skip(1), (Key, Value) => new { Key, Value })
             .Where((pair,index) => index % 2 == 0)
             .ToDictionary(pair => pair.Key, pair => pair.Value);

我已經制作了一個類似的方法來處理這種類型的請求。 但由於你的數組包含鍵和值,我認為你需要先拆分它。

然后你可以使用這樣的東西來組合它們

public static IDictionary<T, T2> ZipMyTwoListToDictionary<T, T2>(IEnumerable<T> listContainingKeys, IEnumerable<T2> listContainingValue)
    {
        return listContainingValue.Zip(listContainingKeys, (value, key) => new { value, key }).ToDictionary(i => i.key, i => i.value);
    }
a.Select((input, index) = >new {index})
  .Where(x=>x.index%2!=0)
  .ToDictionary(x => a[x.index], x => a[x.index+1])

我建議使用for循環,但我已根據您的要求回答..這絕不是整潔/清潔..

public static IEnumerable<T> EveryOther<T>(this IEnumerable<T> source)
{
    bool shouldReturn = true;
    foreach (T item in source)
    {
        if (shouldReturn)
            yield return item;
        shouldReturn = !shouldReturn;
    }
}

public static Dictionary<T, T> MakeDictionary<T>(IEnumerable<T> source)
{
    return source.EveryOther()
        .Zip(source.Skip(1).EveryOther(), (a, b) => new { Key = a, Value = b })
        .ToDictionary(pair => pair.Key, pair => pair.Value);
}

設置方式,並且由於Zip工作方式,如果列表中有奇數個項目,最后一項將被忽略,而不是生成某種異常。

注意:源於此答案。

IEnumerable<string> strArray = new string[] { "name", "Fred", "colour", "green", "sport", "tennis" };


            var even = strArray.ToList().Where((c, i) => (i % 2 == 0)).ToList();
            var odd = strArray.ToList().Where((c, i) => (i % 2 != 0)).ToList();

            Dictionary<string, string> dict = even.ToDictionary(x => x, x => odd[even.IndexOf(x)]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM