Replace few variable names in the string for c# [duplicate] - c#

This question already has answers here:
fastest way to replace string in a template
(9 answers)
Closed 4 months ago.
I have a question, my template content does not have a fixed value, this template content value is random and comes from what the user input and stores in the table, but the variable of the content is set.
For example few template content values (For schedule.TemplateContent) :
1. My name is {name}.
2. My name is {name}. My last name is {lastName}
3. Her name is {name}. She is a {sex}. She like play {activity}
Below is my code, I just only know how to replace 1 word in the template content, not sure how to replace if loop the template content has multiple variables need to replace:
foreach (SAASQueuePatList pat in patList)
{
pat.PatName = "{name}";
pat.PatLastName = "{lastName}";
pat.PatSex= "{sex}";
pat.PatActivity = "{activity}";
string fullContent = schedule.TemplateContent.Replace("{name}", pat.PatName);
}
Hope someone can guide me on how to solve this problem. Thanks.

string fullContent = schedule.TemplateContent
.Replace("{name}", pat.PatName)
.Replace("{lastName}", pat.PatLastName)
.Replace("{sex}", pat.PatSex)
.Replace("{activity}", pat.PatActivity);

You need a map that links a field name to a property.
var map = new Dictionary<string,Func<SAASQueuePat,string>>
{
"name", x => x.PatName,
"sex", x => x.Gender
};
Then you can generate string like this:
foreach (var item in map)
{
template = template.Replace("{" + item.Key + "}", item.Value(pat));
}

Related

Parsing string into key value pairs C# [duplicate]

This question already has answers here:
How can I deserialize JSON with C#?
(19 answers)
Closed 2 years ago.
I have method where I call another API. From
var activeCustomers = await response.Content.ReadAsStringAsync();
I get string which contains [timestamp, value] objects:
{"values":[[1298937600000,1],[1459468800000,16],[1462060800000,527],[1464739200000,173],[1467331200000,132],[1470009600000,166],[1472688000000,151],[1475280000000,172],[1477958400000,139],[1480550400000,129],[1483228800000,116],[1485907200000,133],[1488326400000,180],[1491004800000,227],[1493596800000,281],[1496275200000,263],[1498867200000,230],[1501545600000,326],[1504224000000,403],[1506816000000,442],[1509494400000,1019],[1512086400000,650],[1514764800000,708],[1564617600000,2614],[1567296000000,2527],[1569888000000,3144],[1572566400000,3075],[1575158400000,2541],[1577836800000,2246],[1580515200000,2456],[1583020800000,885]]}
I want to parse these values into key value pairs, but I am not sure what's the most optimal way for that.
I tried removing beginning and ending of string and cast it as object but it stays as one big string inside the ienumerable:
int index = activeCustomers.IndexOf(":");
if (index > 0)
activeCustomers = activeCustomers.Substring(index + 1);
activeCustomers = activeCustomers.Remove(activeCustomers.Length - 1);
var results = ((IEnumerable) activeCustomers).Cast<object>();
I also tried making regex for that but I am not very comfortable with that.
This just a JSON with array of arrays, which can be easily deserialized using Json.NET
var result = JsonConvert.DeserializeObject<Root>(activeCustomers);
or System.Text.Json
var result = JsonSerializer.Deserialize<Root>(activeCustomers);
Where Root is
public class Root
{
public long[][] values { get; set; }
}
Then you can map the values property to any desired structure using Select method
var pairs = result.values.Select(v => new { timestamp = v[0], value = v[1] }).ToList();

Retrieve a value among several json fields if this one is equal to another value of this json [duplicate]

This question already has answers here:
Get values from dynamic JSON properties C#
(2 answers)
Closed 2 years ago.
I'm sorry if I'm asking a trivial question but I'm stuck so I'm asking for your help.
I currently have a dynamic json that I receive, and I would like that according to the value of the phone the corresponding field is retrieved.
For exemple in my foreach(var item in jsonResult),
if item["Phone"].Value = "PSTN"( or "UIFN", "TS", "RS", "TF" ) then I would like to retrieve the json field which corresponds with its value, in this case it would be "PSTN".
If anyone has an idea how I can make this happen.
Thank you in advance for your answers and your help.
I believe this post can help you.
Try this code:
JObject jObject = JObject.Parse(jsonResult);
var result = (JObject)jObject["put here your top node level"];
foreach(JProperty prop in result.Properties())
{
if (prop.Name == item["Phone"].Value)
{
var values = jObject["put here your top node level"][prop.Name].Values<string>(item["Phone"].Value);
// do something
}
}
You could do it like this. thang.json is a file with json you provided.
var json = File.ReadAllText("thang.json");
var deserialized = JsonConvert.DeserializeObject<dynamic>(json);
if (new[] {"PSTN", "UIFN", "TS", "RS", "TF"}.Contains((string) deserialized.Phone))
{
Console.WriteLine(deserialized[(string)deserialized.Phone]);
}

How to get value in dictionary from 2 different string [duplicate]

This question already has answers here:
How can I parse HTTP urls in C#?
(3 answers)
Closed 3 years ago.
I have 2 string
string str="nl/vacature/admin/Employee/home/details/"
and other one
string template ="nl/vacature/{model}/{controller}/{Action}/{Method}/"
I am looking for
model=admin,controller=Employee,Action=home,Method=details
in an object or in dictionary in key-value format.Their URL and template key may be at different order it may be
string template ="vacature/jobcount/{controller}/{Action}/{model}/{Method}/"
string str ="vacature/jobcount/Employee/home/admin/details/"
Try this:
string url = "nl/vacature/admin/Employee/home/details/";
string template = "nl/vacature/{model}/{controller}/{Action}/{Method}/";
// remove unnecessary parts
template = template.Replace("nl/vacature/", "").Replace("{", "").Replace("}", "");
url = url.Replace("nl/vacature/", "");
// dictionary, that will hold pairs, that you want
var dict = new Dictionary<string,string>();
var urlList = url.Split('/');
var templateList = template.Split('/');
for(int i = 0; i < urlList.Length; i++)
{
dict.Add(templateList[i], urlList[i]);
}
I leave to you exception handling in case, that URLs won't consist of the same number of parts.
Here's a Regex solution, but you need to change the template a little bit.
string url = "nl/vacature/admin/Employee/home/details/";
string template = "nl/vacature/(?<Model>.*?)/(?<Controller>.*?)/(?<Action>.*?)/(?<Method>.*?)/";
var matches = Regex.Match(url, template).Groups.Cast<Group>().Where(g => !int.TryParse(g.Name, out _)).ToDictionary(m => m.Name, m => m.Value);
// Dictionary<string, string>(4) { { "Model", "admin" }, { "Controller", "Employee" }, { "Action", "home" }, { "Method", "details" } }
However, external parsing library might be a better fit. You can find some URL parser instead of using regex.

How to get class property name with spaces? [duplicate]

This question already has answers here:
.NET - How can you split a "caps" delimited string into an array?
(19 answers)
Closed 7 years ago.
I have a class:
MyClass
{
public int Id{set;get;}
public string MollName{set;get;}
public string MollAddress{set;get;}
public string MollPRG{set;get;}
}
i use it for generate report in Excel. I makw a whole document programaticaly so i no have any templates.
For make a report's columns names i use:
var fields = typeof(MyClass).GetFields(
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
var names = Array.ConvertAll(fields, field => field.Name).ToList();
var trimedNames = names.Select(name => name.Substring(1, name.IndexOf(">", StringComparison.Ordinal) - 1)).ToList();
foreach (var fieldName in trimedNames)
{
//**some code
}
And i get report with column names:
Id
MollName
MollAddress
MollPRG
How can i get it with spaces?:
Id
Moll Name
Moll Address
Moll PRG
You could try a regex, for sample:
foreach (var fieldName in trimedNames)
{
var fieldNameWithSpaces = Regex.Replace(fieldName, "(\\B[A-Z])", " $1");
// you can use fieldNameWithSpaces here...
}
See this post: .NET - How can you split a "caps" delimited string into an array?

Is there a function to compare a string to a larger string? [duplicate]

This question already has answers here:
Case insensitive 'Contains(string)'
(29 answers)
Closed 9 years ago.
A better way to explain my question is like this
List the names of someone whose names contain a given string. For example, if the given string is "John,", the system will display the names of every person whose name contains "John", such as "John Smith", "Elton Johns", and "johnny H".
I couldn't explain it in the question and trying to find what I'm looking for on Google when I can't phrase is right is difficult
If your search is case-sensitive, you can use Contains:
var name = "John Smith";
if(name.Contains("John"))
{
// Name contains John
}
Or, to get all the names that contain John:
var names = new string[] {"John Smith", "Bob Smith", "Frank"};
var results = names.Where(n => n.Contains("John"));
If you want to ignore the case, you can convert both strings to lowercase:
var results = names.Where(n => n.ToLower().Contains("john"));
You could also implement your own case-insensitive Contains function as an extention method:
public static bool Contains(this string value, string substr, StringComparison c)
{
return value.IndexOf(substr, c) >= 0;
}
Then use:
var results = names.Where(n => n.Contains("John", StringComparison.OrdinalIgnoreCase));
IList<string> lst = new List<string>();
lst.add("John Smith");
lst.add("Elton Johns");
lst.add("mark");
lst.add("jones");
now to get the names contains "John"
var resultList = lst.Where(x => x.Contains("John")).ToList();
Use System.Linq
private static List<String> GetNames(List<string> names ,string name)
{
return names.Where(x => x.ToLower().Contains(name.ToLower())).ToList();
}
Maybe you should also consider uppercasing ( .ToUpper ) and sanitizing ( .Replace(",", "") ) your strings before cheching them with .Contains, otherwise "johny H" wouldn't contain "John,".
We have String.Contains and String.IndexOf.
String.Contains: Returns a value indicating whether the specified
String object occurs within this string.
String.IndexOf: Reports the zero-based index of the first occurrence
of a specified Unicode character or string within this instance. The
method returns -1 if the character or string is not found in this
instance.
Contains is case sensitive so, if you want to give "John" and find "johnny H" it would better use IndexOf
var key = "John";
var names = new[]{"John Smith", "Elton Johns", "johnny H"};
foreach(var name in names)
if(name.IndexOf(key, StringComparison.InvariantCultureIgnoreCase) > -1) {
// Name contains the key
}
If you want to use you Contains should convert both name and key to upper or lower with an appropriate culture info.

Categories