Reputation: 195
I have a string like this:
var info = "status=ACCEPTED&code=12345&type=CARD&id=98765";
How can I in a simple way get info from this string?
Example: I only want to get the "status" value from the string, in this case "ACCEPTED".
Upvotes: 0
Views: 521
Reputation: 849
In case you like less lines of code :)
var info = "status=ACCEPTED&code=12345&type=CARD&id=98765";
var getInfo = new Func<string, string>(x => info.Split('&').Select(y => y.Split('=')).Where(y => y.Length > 1 && y[0] == x).Select(y => y[1]).FirstOrDefault());
Now simply call it as -
var a = getInfo("status");
var b = getInfo("id");
var c = getInfo("something");
Result -
a = ACCEPTED
b = 98765
c = null
Concept is same, split by &
then by =
. I am using LINQ to get the result.
Upvotes: 1
Reputation: 1664
using Linq:
var info = "status=ACCEPTED&code=12345&type=CARD&id=98765";
var field = "status";
var value = info.Split('&').Select(i => i.Split('='))
.Where(f => f[0].Equals(field)).Select(f => f[1]).FirstOrDefault();
Upvotes: 1
Reputation: 296
First split by '&' then split by = and create dictionary out of it.
Below is a c# code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
Program prog = new Program();
Dictionary<String,String> output = prog.splitString("status=ACCEPTED&code=12345&type=CARD&id=98765");
Console.WriteLine(output["status"]);
}
public Dictionary<string,string> splitString(string text) {
Dictionary<string,string> output = new Dictionary<string,string>();
if(text != null) {
string[] keyValueArray = text.Split('&');
foreach(string keyVal in keyValueArray) {
string[] finalSplit = keyVal.Split('=');
output.Add(finalSplit[0],finalSplit[1]);
}
}
return output;
}
}
}
Upvotes: 1
Reputation: 3498
you can take advantage of Linq Split
then convert it to List
to be finalized into a Dictionary<string, string>
.
You can also create a simple model to convert it to object.
this is a simple helper method will do what you need :
public IDictionary<string, string> GetInfo(string info)
{
var infoDic = new Dictionary<string, string>();
var str = info.Split('&').ToList();
for (int x = 0; x < str.Count; x++)
{
var pair = str[x].Split('=');
infoDic.Add(pair[0], pair[1]);
}
return infoDic;
}
usage :
var info = "status=ACCEPTED&code=12345&type=CARD&id=98765";
var result = GetInfo(info);
var status = result.Where(x => x.Key.ToLower() == "status")
.Select(x => x.Value)
.First()
.ToString();
Upvotes: 0
Reputation: 916
Use the HttpUtility.ParseQueryString() method like this:
var parsed = HttpUtility.ParseQueryString(info);
// now you can use parsed["status"], parsed["code"], parsed["type"], and parsed["id"], which will all be strings
Upvotes: 2