简体   繁体   中英

Extracting Value From A String in C# Visual Studio

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

Using Linq

You can check/run this code on https://do.netfiddle.net/pYtUUl

Full example code

using System;
using System.Linq;
using System.Collections.Generic;

namespace License
{
    public static class Utils
    {
        public static string GetValue(string key, 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 => //Using the extension function SelectWhere declared above.
            {
                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].Trim(),
                    Value = value.Length < 2 ? string.Empty : value[1] //Check if element has 2 elements after split. if length < 2 value is empty string.
                };
            })
            .Where(element => element.Key.Equals(key)) //Filter elements with key value
            .Select(element => element.Value) //Select the value
            .FirstOrDefault();  //Get the first ocurrence or null.
        }

    }

    public class Program
    {
        public static void Main(string[] args)
        {
            string key = "Mac Q";

            string rawValues = "C=True[##]V=True[##]PAN=True[##]Mac Q[##]A=True"; //Mac Q is empty
            string value = Utils.GetValue(key, rawValues); //Calling to the function
            Console.WriteLine(value == null ? $@"""{key}"" value not found." : $@"Mac Q value is ""{value}""");

            rawValues = "C=True[##]V=True[##]PAN=True[##]A=True"; //Mac Q is not present.
            value = Utils.GetValue(key, rawValues); 
            Console.WriteLine(value == null ? $@"""{key}"" value not found." : $@"Mac Q value is ""{value}""");

            rawValues = "C=True[##]V=True[##]PAN=True[##]Mac Q=3[##]A=True"; //Mac Q is present with value
            value = Utils.GetValue(key, rawValues); 
            Console.WriteLine(value == null ? $@"""{key}"" value not found." : $@"Mac Q value is ""{value}""");

            Console.ReadLine();
        }
    }
}

Output

Mac Q value is ""
"Mac Q" value not found.
Mac Q value is "3"

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}");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM