代码之家  ›  专栏  ›  技术社区  ›  Ulisses Farias

在c中拆分字典中的“路径变量”字符串#

  •  0
  • Ulisses Farias  · 技术社区  · 1 年前

    我想断开绳子:

    value1/672/value2/32/value3/21413
    

    在一个

    Dictionary<string, string>
    

    如果不使用for循环,我怎么能做到这一点?

    2 回复  |  直到 1 年前
        1
  •  0
  •   SELA    1 年前

    假设提供的字符串包含第一个值作为关键字,第二个值是提供的字符串中的值

    value1/672/value2/32/value3/21413
    

    以下是实现上述目标的方法:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    
    class Program
    {
        static void Main()
        {
            string input = "value1/672/value2/32/value3/21413";
            string[] parts = input.Split('/');
            var dictionary = parts
                .Select((value, index) => new { value, index })
                .Where(x => x.index % 2 == 0) // Select only even indexed elements as keys
                .ToDictionary(x => x.value, x => parts[x.index + 1]); // Use the next element as value      
            
            foreach (var kvp in dictionary)   // Loop for printing the result only
            {
                Console.WriteLine($"{kvp.Key}: {kvp.Value}");   // Output the dictionary key and values
            }
        }
    }
    

    参考正在工作的.netfiddle here

        2
  •  0
  •   Ronan Thibaudau    1 年前

    如果你真的想这样做,你可以用几个LINQ操作符来完成,但我看不出有太多附加值:

    var str = "value1/672/value2/32/value3/21413";
    
    // Array containing [value1, 672, value2, 32, value3, 21413
    var arr = str.Split('/');
    
    arr
        // Zip gives you pairs between 2 collections, here i'm zipping arr with itself with first element skipped
        // this gives both the key => value but also the value=> key pairs
        // so this results in {value1, 672} which we want, but also in {672, value2} which we do not want
        .Zip(arr.Skip(1))
        // Keep only the even indexes to get rid of the pairs we don't want mentioned above
        .Where((item,index)=>index%2 == 0)
        // Convert those tuples to a dictionnary
        .ToDictionary(item=>item.First,item=>item.Second);