Winforms C# change string text order - c#

I am new to C# and I get the user's name that is system generated and it comes in the format:
LastName, FirstName
I want to change this to be added to a database
FirstName.LastName
I am totally stuck on how to do this, any help would be great,

If the order always comes as "Lastname, Firstname", the following code should work:
var variableContainingLastNameFirstName = "LastName, FirstName";
var split = variableContainingLastNameFirstName.Split(new char[] {',' });
var firstNamelastName = string.Format("{0}, {1}", split[0], split[1]);

Try this:
string username = "LastName, FirstName";
string[] words = username.Split(new string[]{", "});
string result = words[1] + "." + words[0]; // storing
// for output
Console.WriteLine("{0}.{1}", words[1], words[0]);
Console.WriteLine(result);

Related

splitting one item in listBox into two Items

I have a problem with my code, I am supposed to import a list from a .txt file, each line in the txt file has two item, name and city for example
Alex###London
Justin###Texas
I have a code that imports this list from the txt file into the listBox1 but I can not split Alex and London. My class is User and I want to add Alex to name and London to City.
this is the code I use but it doesnt work
List<User> userList = new List<User>();
var charArray = listBox1.Text.Split('#' + "#" + "#");
string Name = charArray[0];
string City = charArray[1];
User user = new User(Name, City);
userList.Add(user);
You can Split by a string with multiple chars, for example with this overload:
string[] nameAndCity = listBox1.Text.Split(new[]{"###", StringSplitOptions.None});
its very strange way to store your data this, if u write it by yourself dont do this, better store data in JSON or XMS, rewrite it if u can, with your data structure u can do this
var yourData = "Alex###London Justin###Texas\nJustin1###Texas1 Justin2###Texas2";
var separators = new string[] { "\n", " " };
var stringUsers = yourData.Split(separators, StringSplitOptions.RemoveEmptyEntries);
foreach(var stringUser in stringUsers)
{
var userData = stringUser.Split("###");
string Name = userData[0];
string City = userData[1];
Guldkort user = new Guldkort(Name, City);
userList.Add(user);
}
check if i understood your data structure right and if your input data is correct

How to configure the return string based on user input?

I have a scenario where I am supposed to add a feature to the existing code and this feature is supposed to take input of from the user and form a string. Right now by default the code ships with full name = firstname and lastname. But I am supposed to make it configurable according to user demand, where the user can add any property like location or phone number to display with the full name. So for e.g the format can be [firstname + lastname + location or lastname + firstname + phonenumber ].
And I have managed to take the users input and store it in a variable called test and here is the code for it.
[DataMember]
public string FullName
{
get
{
string test = "";
test = Services.GetService<IGlobalOptionsBrokerDataAccess>().test1();
return string.Format("{0} {1} {2}", this.FirstName, this.MiddleName, this.LastName);
}
set
{
_fullName = value;
}
}
So how can I make it work dynamically? Here the screenshot of how the value is available in the test variable. If the user wants to have ManagerID then how can I make it work dynamically?
Is there anything more I should provide so that it would be easier for you guys out there?
May not be an optimal solution, but this is what I thought of quickly. Making your format string dynamic could help you.
var posDict = new Dictionary<string, string> {
{"FirstName","{0}" },
{"MiddleName","{1}" },
{"LastName","{2}" }};
var test = "FirstName,LastName,MiddleName";
var posString = "";
foreach (var prop in test.Split(','))
posString += $"{posDict.First(x => x.Key == prop).Value} ";
return string.Format(posString, this.FirstName, this.MiddleName, this.LastName);
I found a better solution other than the mentioned above.
string[] columnNames = format.Split(new char[] { ',' });
string userFullNameAsPerFormat = string.Empty;
string defaultFullName = this.FirstName + " " + this.LastName;
// Get the Type object corresponding to MyClass.
Type myType = typeof(Courion.BusinessServices.Access.ProfileDTO);
// Get the PropertyInfo object by passing the property name.
PropertyInfo myPropInfo = myType.GetProperty(item.Trim());
userFullNameAsPerFormat += (string) myPropInfo.GetValue(this) + " ";

Convert List Combo into Comma-Separated String in c#

My code is as below:
List<string> colorList = new List<string>();
....
sCombo = reader["Combo"].ToString();
colorList.Add(sCombo.ToString());
....
foreach (var Combo in colorList)
{
Response.Write(string.Join(",", Combo));
}
Output: D410D430D440D420 instead of D410,D430,D440,D420
What is the most simple way to convert the List<string> into a comma-separated string?
EDIT #01
Your suggestion working, but I need this new output :
'D410','D430','D440','D420'
Because use this string on sql query.
Thank you
I think this would be very handy
var colorList = new List<string>() { "D410", "D430", "D440", "D420" };
string commaSeparated = string.Join(",", colorList);
Console.WriteLine(commaSeparated);
or try solution based on Linq
Console.WriteLine(colorList.Select(s => s + ",").Aggregate((s, q) => s + q).TrimEnd(','));
The output
D410,D430,D440,D420
Edit
string result = string.Join(",", colorList.Select(e => "'" + e + "'"));
Console.WriteLine(result);
will give you
'D410','D430','D440','D420'
Without a foreach:
Response.Write(string.Join(",", colorList));
You need to output like this => 'D410','D430','D440','D420'
So try below,
string result = string.Join(",", colorList.Select(x => $"'{x}'"));
Response.Write(result);
What we did above?
Answer: First we flatten each item in your list with a single quoted ('') surrounding string and then we just pass this newly generated flatten result to join method of string with a comma (,) to get your desired output.
Output: (From Debugger)

Convert list to string with single quotes

I am trying to create a string from List
This is my code
List<string> SelectedSalesmen = new List<string>();
and I am adding selected salesmen from listBox like this
foreach (ListItem lst in lstBoxSalesmen.Items)
{
if (lst.Selected)
{
SelectedSalesmen.Add(lst.Value);
}
}
finally I am storing that value to a string like this
string SalesManCode = string.Join(",", SelectedSalesmen.ToArray());
But I am getting like this
SLM001,SLM002,SLM003
but I need Output like this
'SLM001','SLM002','SLM003'
Try this:
string SalesManCode = string.Join(",", SelectedSalesmen
.Select(x=>string.Format("'{0}'",x)));
it will wrap all your elements with ' and then join them using , as separator
What about this:
string output = "'" + string.Join("','", SelectedSalesmen) + "'";
Though this'll return '' for an empty input.
Same as the answer from #wudzik but with string interpolation
var salesManCode = string.Join(",", selectedSalesmen.Select(x => $"'{x}'"));
Just use the above one with split like below:
string.Join(",", SelectedSalesmen.Split(',').Select(x => string.Format("'{0}'", x)));
which will give you:
"'SLM001','SLM002','SLM003'"
you can do something like this:
"'" + string.Joing("',", SelectedSalesmen.ToArray() + "'");

Adding string in front and at end of a list

I have list of names:
IEnumerable<Name> names;
names = n.GetNames(abc);
It gets list like: Ken, John, Sam,... I want it to show like this:
'Ken', 'John', 'Sam',...
I tried this:
string s = string.Join("',", names); but it gives result like:
Ken', John', Sam',...
Is there a way to add "'" in front of these names in single line of code?
Try this.
string s = string.Join(",", names.Select(s => string.Format("'{0}'", s)).ToArray());
I think you were almost there:
string s = "'" + string.Join("','", names) + "'";

Categories

Resources