I'm thinking about an application that builds some kind of usernames depending on the category where the user belongs. The problem starts when I try to generate this username from a rule contained in a table.
Example:
| ID | Name | City | Level | Rule |
|----|-------|--------|--------|------|
| 1 | John | London | A | 1 |
| 2 | Chris | Paris | C | 1 |
| 3 | Anna | Madrid | B | 3 |
| 4 | Marie | Roma | C | 2 |
| Rule | Format |
|------|-----------------------------|
| 1 | "Name + City" |
| 2 | "Name[0] + City[0] + Level" |
| 3 | "Name[0] + \".\" + City" |
And I would like to get as a final result:
| ID | Username |
|----|------------|
| 1 | JonhLondon |
| 2 | ChrisParis |
| 3 | A.Madrid |
| 4 | MRC |
So I was thinking if there is a nice method that can build the username using the string contained in the rules table as the template to do it like:
string Name = dtData[i].Name;
string City = dtData[i].City;
string Level = dtData[i].Level;
string u = SomeGreatMethodToEvaluate(dtRules[dtData[i].Rule].Format);
dtFinal[i].Username = u;
Sorry if I didn't explain it good enough, but it's a tricky thing for me.
I would try to leverage String.Format
to do this. You would store the format string in the database and pass in the parameters in a consistent way, e.g. Name, City, Level, Rule. A pattern like "Name + City"
becomes pretty easy, it just requires the format string "{0}{1}"
.
String.Format
doesn't support taking parts of Strings
out of the box, but you can extend its functionality with an IFormatProvider
and a custom class to wrap your strings. There are good pointers in the related question: Can maximum number of characters be defined in C# format strings like in C printf?.