Stringbuilder add new line inside foreach loop - c#

I'm trying to add a new line after looping through the group names inside of a foreach loop. However, it never adds the new line. Everything is printed in single line.
string [] groups = client.GetGroups(username.TrimEnd());
StringBuilder groupNames = new StringBuilder();
foreach (string groupName in groups)
{
groupNames.Append(string.Format(groupName,Environment.NewLine));
}
Label1.Text = groupNames.ToString();
After reading few questions posted here in SO, I have tried many different solutions such as:
{
groupNames.Append(groupName);
groupNames.AppendLine();
}
Label1.Text = groupNames.ToString();
Also tried:
{
groupNames.Append(groupName);
groupNames.Append(System.Environment.NewLine);
}
Label1.Text = groupNames.ToString();
However, if in any of the solution I add:
groupNames.Append("|");
//or
groupNames.Append(",");
it will work. The only thing is not working is the newline.
One thing to note is I'm grabbing the users groupNames from Active Directory and when the groupNames returned it contains \ in the name. I also tried removing the \ before adding new line, didn't work either.
groupNames.Append(groupName);
groupNames.Replace(#"\", " ");
groupNames.Append(System.Environment.NewLine);
Any suggestions?

In html new line is not \r\n but it's <br>, so you need to add <br> after each element, a simple string.Join should work fine:
var result = string.Join("<br>", groups);

Related

Get all class name icon from fontawesome

I'd like to get all class name icon from fontawesome to list or array in c# from fontawesome.
I'd like to get all variants icon for example:
fas fa-abacus
far fa-abacus
fal fa-abacus
...
I tried to extract it from the css file, but it only gets the icon names themselves without prefixes.
var text = File.ReadAllText(#"fontawesome\all.css");
var allMatches = Regex.Matches(text, #"^\.fa\-(.*):", RegexOptions.Multiline);
Thank's for help.
Monika
public List<string> ListOfFontAwesomeIcons(string FilePath)
{
List<string> response = new List<string>();
List<string> fontAwesomePrefixes = new { "fas", "far" /*manually add all prefixes*/ }
var textLines = File.ReadAllLines($"{FilePath}");
foreach(string l in textLines)
{
foreach(string p in fontAwesomePrefixes)
{
if(l.Contains(p))
response.Add(l.Replace($"{p} "));
}
}
return response;
}
I ran this in C# 9, VS2019 just based off of feeding it a test string, and it worked for me. I double-checked for fa- in the result list to make sure I excluded all of the other results.
Also, I just converted to List of strings for display. You don't really need to do that, depending on what you're doing with your results.
EDIT: Code updated to reflect FA's .css file available on their website, not the format of the string I was using earlier.
Replace the path in the first line with whatever reflects your project. Note that there are faster methods than ReadAllText, but it should be fine for this.
string text = System.IO.File.ReadAllText("./wwwroot/css/all.css");
var allMatches = Regex.Matches(text, "(?<=[.]).*?(fa-)?.*?(?=[:])", RegexOptions.None);
List<string> allMatchesStrings = new();
foreach (var item in allMatches)
{
if (item.ToString().Contains("fa-"))
allMatchesStrings.Add(item.ToString());
}
foreach (var item in allMatchesStrings)
{
Console.WriteLine(item);
}

C# Add 2 comboBox to csv text file

Am close with this but it still failing. Just adds combobox1 item many times then changes. Combobox2 gets added correctly for each entry of cbo1.
Also adds the delimiter , at front of line in MyFile.txt
I load this with a split no problem, going back is the trouble
I'm like new real new C#.
StreamWriter OutFile = new StreamWriter("MyFile.txt",false);
foreach(object L in comboBox1.Items)
foreach(object M in comboBox2.Items)
{
string lineoftext1 = (L.ToString());
string lineoftext2 = (",");
string lineoftext3 = (M.ToString());
string joinedText;
joinedText = String.Join(lineoftext1, lineoftext2, lineoftext3);
//MessageBox.Show(joinedText);
OutFile.WriteLine(joinedText);
}
OutFile.Close();
OOOOH, i see the problem, it's in the way you are handling your strings, you don't use string.join that way, you can either join them explicitly like this:
joinedText = lineoftext1 + lineoftext2 + lineoftext3;
or you need to create something that the join method accepts, i would use a list, so the inside of your foreach loop would look like this
List<string> mystrings = new List<string>();
mystrings.add(L.ToString());
mystrings.add(M.ToString());
joinedText = String.Join(",", mystrings);
alternativly you could leave it how you have it, but change some values around
joinedText = String.Join(lineoftext2, lineoftext1, lineoftext3);
The first parameter passed to String.Join is the seperator. you were passing it the text.
If this doesn't help, then i would want to see your expected output as i mentioned in my comments above.
Edit: Try this if you want a 1-1 2-2 style
int i = 0;
foreach (object M in comboBox1.Items)
{
List<string> mystrings = new List<string>();
mystrings.Add(comboBox2.Items[i].ToString());
mystrings.Add(M.ToString());
OutFile.WriteLine(String.Join(",", mystrings));
i++;
}
just be aware, this will error if there are different numbers of items in each combobox. (you will get an outside array bounds error)
I am not sure , i think in your combobox1, same items are added when a post back is done, so it repeats back to combobox1 even any changes happens in combobox2. If this is your question, you can overcome this by adding your code inside, if (!IsPostBack), something like this,
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//write you code here
}
}
Nikerym you got it man I just added combobox1 below
129 lines as was the original
Thanks M8
StreamWriter OutFile = new StreamWriter("MyFile.txt", false);
int i = 0;
foreach (object M in comboBox1.Items)
{
List<string> mystrings = new List<string>();
mystrings.Add(comboBox1.Items[i].ToString());
mystrings.Add(comboBox2.Items[i].ToString());
OutFile.WriteLine(String.Join(",", mystrings));
i++;
}
OutFile.Close();

how to remove blank spaces from a list when you remove item from a list

I am reading a file in my winform and saving it in a list.i have a button "remove" and on clicking it an item (each list item is a line from the file) from the list is removeed and when i write back this list to a file the items i have removed are replaceed by a blank line.
I don't want these blank lines in my file. can anyone please tell me how to remove them.
I have tried using list.Remove(item) to remove the item from the list.
here is what i have tried...
ListView.CheckedListViewItemCollection chkditems = listView1.CheckedItems;
Regex regex1 = new Regex(".*\"(?<vm_name>.*)\".*:.*{.*\"vmx_path\".*:.*r?\"(?<vmx_path>.*)\",.*\"vm_base\".*:.*r?\"(?<vm_base>.*)\".*");
List<string> list_to_items = new List<string>();
foreach (ListViewItem chkitem in chkditems)
{
foreach (string line in list)
{
Match match1 = regex1.Match(line);
if (match1.Success)
{
if (match1.Groups["vm_name"].Value == chkitem.Text)
{
list_to_items.Add(line);
}
}
}
listView1.Items.Remove(chkitem);
}
foreach (string tormv in index)
{
list.Remove(tormv);
}
for sample data for the list you can consider it containing any text.
Should be a comment, but with code, it's difficult...
I don't know what you're doing, but if you run this code, you'll see that the assumptions of your question are incorrect:
var list = new List<string>{"1","2","3"};
Console.WriteLine(string.Join(", ", list)); // 1, 2, 3
list.Remove("2");
Console.WriteLine(string.Join(", ", list)); // 1, 3

Removing duplicate words in url and filtering out words not in a list

I have a links that the sub category got repeated a bunch of times. Also only want to keep the repeating if they are in a certain list. But also keep the last part of the link
About
Video
Example1
Example2
www.example.com/About/About/Videos/Videos/Videos/Featured/5-great-videos
should be
www.example.com/about/videos/5-great-videos
Any help?
How about this one, using LINQ
string str = "www.example.com/About/About/Videos/Videos/Videos/Featured/5-great-videos";
var result = str.Split('/').GroupBy(x=>x).Select(x=>x.Key).Aggregate((a,b)=>a+"/"+b);
In case you prefer not using linq:
string url = "www.example.com/About/About/Videos/Videos/Videos/Featured/5-great-videos";
List<string> urlList = new List<string>();
foreach (string urlToken in url.Split('/'))
if (!urlList.Contains(urlToken)) urlList.Add(urlToken);
url = String.Join("/", urlList.ToArray());

C# - Problem removing items in List1 & List2 from List3

I have a file that I am reading in, splitting up into different lists and outputting them into RichTextBox to then be read into 3 different Listboxes. I am currently doing all of this, however I have come across something I do not know how to fix/work around.
My code is below and I seem to be having trouble understanding why it fails to properly work when it gets to the Match twoRegex = Regex.Match(...) section of the code.
CODE:
private void SortDataLines()
{
try
{
// Reads the lines in the file to format.
var fileReader = File.OpenText(openGCFile.FileName);
// Creates a list for the lines to be stored in.
var placementUserDefinedList = new List<string>();
// Reads the first line and does nothing with it.
fileReader.ReadLine();
// Adds each line in the file to the list.
while (true)
{
var line = fileReader.ReadLine();
if (line == null)
break;
placementUserDefinedList.Add(line);
}
// Creates new lists to hold certain matches for each list.
var oneResult = new List<string>();
var twoResult = new List<string>();
var mainResult = new List<string>();
foreach (var userLine in placementUserDefinedList)
mainResult.Add(string.Join(" ", userLine));
foreach (var oneLine in mainResult)
{
// PLACEMENT ONE Regex
Match oneRegex = Regex.Match(oneLine, #"^.+(RES|0402|0201|0603|0805|1206|1306|1608|3216|2551"
+ #"|1913|1313|2513|5125|2525|5619|3813|1508|6431|2512|1505|2208|1005|1010|2010|0505|0705"
+ #"|1020|1812|2225|5764|4532|1210|0816|0363|SOT)");
if (oneRegex.Success)
oneResult.Add(string.Join(" ", oneLine));
}
//
// THIS IS THE SECTION THAT FAILS..
//
foreach(var twoLine in mainResult)
{
//PLACEMENT TWO Regex
Match twoRegex = Regex.Match(twoLine, #"^.+(BGA|SOP8|QSOP|TQSOP|SOIC16|SOIC12|SOIC8|SO8|SO08"
+ #"CQFP|LCC|LGA|OSCCC|PLCC|QFN|QFP|SOJ|SON");
if (twoRegex.Success)
twoResult.Add(string.Join(" ", twoLine));
}
// Removes the matched values from both of the Regex used above.
List<string> userResult = mainResult.Except(oneResult).ToList();
userResult = userResult.Except(twoResult).ToList();
// Prints the proper values into the assigned RichTextBoxes.
foreach (var line in userResult)
userDefinedRichTextBox.AppendText(line + "\n");
foreach (var line in oneResult)
placementOneRichTextBox.AppendText(line + "\n");
foreach (var line in twoResult)
placementTwoRichTextBox.AppendText(line + "\n");
}
// Catches an exception if the file was not opened.
catch (Exception)
{
MessageBox.Show("Could not match any regex values.", "Regular Expression Match Error",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
QUESTIONS:
Does anyone understand why I am unable to to find, or fail at, the second set of REGEX?
With that, is there a way to fix it?
Suggestions please! :)
Haven't you missed the pipeline character in your second regex between two lines?
Match twoRegex = Regex.Match(twoLine, #"^.+(BGA|SOP8|QSOP|TQSOP|SOIC16|SOIC12|SOIC8|SO8|SO08"
+ #"|CQFP|LCC|LGA|OSCCC|PLCC|QFN|QFP|SOJ|SON)");

Categories

Resources