Home > Back-end >  Extracting Value From A String in C# Visual Studio
Extracting Value From A String in C# Visual Studio

Time:03-30

public static string GetMacQ(string rawValues)
    {
        return rawValues.Split('#')
        .Select(element =>
        {
            var value = element.Split('='); 
            return new 
            {
                Key = value[0],
                Value = value[1],
            };
        })
        .Where(element => element.Key.Equals("Mac Q")) 
        .Select(element => element.Value) 
        .FirstOrDefault();  
    }

This code is for splitting the strings, but the problem here is it does not return the value of the key

CodePudding user response:

Using Linq

Full example code

using System;
using System.Linq;

namespace License
{
    public class Utils
    {
        public static string GetMacQ(string rawValues)
        {
            return rawValues.Split("[##]")// Split the string with [##] separator. e.g. ["C=True", "V=True", "PAN=True", "Mac Q=3", "A=True"]
            .Select(element =>
            {
                var value = element.Split("="); //Split the string with = separator. e.g. / ["C", "True"] / ["PAN", "True"] / ["Mac Q", "3"]
                return new //Creating new anonymous object with Key and Value properties. e.g { Key : "Mac Q", Value: "3"}
                {
                    Key = value[0],
                    Value = value[1]
                };
            })
            .Where(element => element.Key.Equals("Mac Q")) //Filter elements with "Mac Q" key
            .Select(element => element.Value) //Select the value
            .FirstOrDefault();  //Get the first ocurrence or null.
        }

    }

    public class Program
    {
        public static void Main(string[] args)
        {
            var rawValues = "C=True[##]V=True[##]PAN=True[##]Mac Q=3[##]A=True";
            string MacQElement = Utils.GetMacQ(rawValues);
            Console.WriteLine(MacQElement == null ? @"""Mac Q"" value not found." : MacQElement);
            Console.ReadLine();

        }
    }
}

Output

3

CodePudding user response:

Here is the code:

// The string to be parsed.As can be seen in the string, this is some key/value pairs, which are separated by [##]
var subkey = "C=True[##]V=True[##]PAN=True[##]Mac Q=3[##]A=True";

// Here we split the string by the separator [##]
var pairs = subkey.Split("[##]");

// Now let's create a storage to store the key/values
var dic = new Dictionary<string, string>();

foreach (var pair in pairs)
{
    // The keys and values are separated by "=". So we split them by the separator.
    var split = pair.Split("=");
    // Now let's add the to the storage
    dic.Add(split[0], split[1]);
}

// OK. done. Let's verify the result.
foreach(var item in dic)
{
    Console.WriteLine($"{item.Key}={item.Value}");
}
  • Related