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

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?

Related

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

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

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();

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.

Return an object depending on matching parameter [duplicate]

This question already has answers here:
LINQ return items in a List that matches any Names (string) in another list
(5 answers)
Closed 8 years ago.
To make my long story short i had to improvise this code a little:
public class Faerie
{
public string Name;
}
public class Example
{
List<Faerie> faeries = new List<Faerie>() {
new Faerie { Name = "Wild Faerie" } ,
new Faerie { Name = "Smoke Faerie" },
new Faerie { Name = "Red Faerie" }
};
string[] faerieNamesFromInput = new string[] { "White Faerie", "Wild Faerie", "Dark Faerie" };
public Faerie ReturnMatchedFromInput()
{
}
}
How can i return a Fairy object from the fairies list if its name matches a name from the user input? Like for instance, here i want to return the Faerie with name Wild Faerie because it's name matches.Is there a short LINQ way for that or i have to go with for loop?
If you want to return multiple matches
faeries.Where(x => faerieNamesFromInput.Contains(x.Name));
If you want to return the first matched then
faeries.FirstOrDefault(x => faerieNamesFromInput.Contains(x.Name));
Simply do
var result = faeries.FirstOrDefault(x => faerieNamesFromInput.Contains(x.Name));
Make sure to include System.LINQ namespace.

How to get string list of Enum descriptions? [duplicate]

This question already has answers here:
Enum ToString with user friendly strings
(25 answers)
Closed 4 years ago.
How can I get a List of an Enum's values?
For example, I have the following:
public enum ContactSubjects
{
[Description("General Question")]
General,
[Description("Availability/Reservation")]
Reservation,
[Description("Other Issue")]
Other
}
What I need to be able to do is pass ContactSubject.General as an argument and it returns the List of the descriptions.
This method needs to work with any Enum, not just ContactSubject (in my example). The signature should be something like GetEnumDescriptions(Enum value).
Something like that may work:
private static IEnumerable<string> GetDescriptions(Type type)
{
var descs = new List<string>();
var names = Enum.GetNames(type);
foreach (var name in names)
{
var field = type.GetField(name);
var fds = field.GetCustomAttributes(typeof(DescriptionAttribute), true);
foreach (DescriptionAttribute fd in fds)
{
descs.Add(fd.Description);
}
}
return descs;
}
however you may review some logic there: such as is it ok to start of names? how are you going to handle multiple Description attributes? What if some of them are missing - do you want a name or just skip it like above? etc.
just reviewed your question. For the VALUE you would have something like that:
private static IEnumerable<string> GetDescriptions(Enum value)
{
var descs = new List<string>();
var type = value.GetType();
var name = Enum.GetName(type, value);
var field = type.GetField(name);
var fds = field.GetCustomAttributes(typeof(DescriptionAttribute), true);
foreach (DescriptionAttribute fd in fds)
{
descs.Add(fd.Description);
}
return descs;
}
however it is not possible to place two Description attributes on single field, so I guess it may return just string.

Categories