While searching mail in Google, we use the sytax like
from:devcoder hasattachments:true mySearchString on:11-aug
or
mySearchString from:devcoder on:11-aug anotherSearchKeyword
After parsing, I should get the keyvalue pair such as (from, devcoder), (on, 11-aug). What is the best way to implement this parsing in c#.
key-value store, or key-value database is a simple database that uses an associative array (think of a map or dictionary) as the fundamental data model where each key is associated with one and only one value in a collection. This relationship is referred to as a key-value pair.
A key-value pair consists of two related data elements: A key, which is a constant that defines the data set (e.g., gender, color, price), and a value, which is a variable that belongs to the set (e.g., male/female, green, 100).
To Linq-ify Jason's answer:
string s = "from:devcoder hasattachments:true mySearchString on:11-aug";
var keyValuePairs = s.Split(' ')
.Select(x => x.Split(':'))
.Where(x => x.Length == 2)
.ToDictionary(x => x.First(), x => x.Last());
Split by space, then for each component of the split, split it by :
. Then proceed accordingly. Roughly:
string s = "from:devcoder hasattachments:true mySearchString on:11-aug";
var components = s.Split(' ');
var blocks = components.Select(component => component.Split(':'));
foreach(var block in blocks) {
if(block.Length == 1) {
Console.WriteLine("Found {0}", block[0]);
}
else {
Console.WriteLine(
"Found key-value pair key = {0}, value = {1}",
block[0],
block[1]
);
}
}
Output:
Found key-value pair key = from, value = devcoder
Found key-value pair key = hasattachments, value = true
Found mySearchString
Found key-value pair key = on, value = 11-aug
Output from your second string:
Found mySearchString
Found key-value pair key = from, value = devcoder
Found key-value pair key = on, value = 11-aug
Found anotherSearchKeyword
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With