Get all class name icon from fontawesome - c#

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

Related

check if string contains dictionary keys and replace the matching subtring with Values from dictionary

I am parsing a template file which will contain certain keys that I need to map values to. Take a line from the file for example:
Field InspectionStationID 3 {"PVA TePla #WSM#", "sw#data.tool_context.TOOL_SOFTWARE_VERSION#", "#data.context.TOOL_ENTITY#"}
I need to replace the string within the # symbols with values from a dictionary.
So there can be multiple keys from the dictionary. However, not all strings inside the # are in the dictionary so for those, I will have to replace them with empty string.
I cant seem to find a way to do this. And yes I have looked at this solution:
check if string contains dictionary Key -> remove key and add value
For now what I have is this (where I read from the template file line by line and then write to a different file):
string line = string.Empty;
var dict = new Dictionary<string, string>() {
{ "data.tool_context.TOOL_SOFTWARE_VERSION", "sw0.2.002" },
{"data.context.TOOL_ENTITY", "WSM102" }
};
StringBuilder inputText = new StringBuilder();
StreamWriter writeKlarf = new StreamWriter(klarfOutputNameActual);
using (StreamReader sr = new StreamReader(WSMTemplatePath))
{
while((line = sr.ReadLine()) != null)
{
//Console.WriteLine(line);
if (line.Contains("#"))
{
}
else
{
writeKlarf.WriteLine(line)
}
}
}
writeKlarf.Close();
THe idea is that for each line, replace the string within the # and the # with match values from the dictionary if the #string# is inside the dictionary. How can I do this?
Sample Output Given the line above:
Field InspectionStationID 3 {"PVA TePla", "sw0.2.002", "WSM102"}
Here because #WSM# is not the dictionary, it is replaced with empty string
One more thing, this logic only applies to the first qurter of the file. The rest of the file will have other data that will need to be entered via another logic so I am not sure if it makes sense to read the whole file in into memory just for the header section?
Here's a quick example that I wrote for you, hopefully this is what you're asking for.
This will let you have a <string, string> Dictionary, check for the Key inside of a delimiter, and if the text inside of the delimiter matches the Dictionary key, it will replace the text. It won't edit any of the inputted strings that don't have any matches.
If you want to delete the unmatched value instead of leaving it alone, replace the kvp.Value in the line.Replace() with String.Empty
var dict = new Dictionary<string, string>() {
{ "test", "cool test" }
};
string line = "#test# is now replaced.";
foreach (var kvp in dict)
{
string split = line.Split('#')[1];
if (split == kvp.Key)
{
line = line.Replace($"#{split}#", kvp.Value);
}
Console.WriteLine(line);
}
Console.ReadLine();
If you had a list of tuple that were the find and replace, you can read the file, replace each, and then rewrite the file
var frs = new List<(string F, string R)>(){
("#data.tool_context.TOOL_SOFTWARE_VERSION#", "sw0.2.002"),
("#otherfield#", "replacement here")
};
var i = File.ReadAllText("path");
frs.ForEach(fr => i = i.Replace(fr.F,fr.R));
File.WriteAllText("path2", i);
The choice to use a list vs dictionary is fairly arbitrary; List has a ForEach method but it could just as easily be a foreach loop on a dictionary. I included the ## in the find string because I got the impression the output is not supposed to contain ##..
This version leaves alone any template parameters that aren't available
You can try matching #...# keys with a help of regular expressions:
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
...
static string MyReplace(string value, IDictionary<string, string> subs) => Regex
.Replace(value, "#[^#]*#", match => subs.TryGetValue(
match.Value.Substring(1, match.Value.Length - 2), out var item) ? item : "");
then you can apply it to the file: we read file's lines, process them with a help of Linq and write them into another file.
var dict = new Dictionary<string, string>() {
{"data.tool_context.TOOL_SOFTWARE_VERSION", "sw0.2.002" },
{"data.context.TOOL_ENTITY", "WSM102" },
};
File.WriteAllLines(klarfOutputNameActual, File
.ReadLines(WSMTemplatePath)
.Select(line => MyReplace(line, dict)));
Edit: If you want to switch off MyReplace from some line on
bool doReplace = true;
File.WriteAllLines(klarfOutputNameActual, File
.ReadLines(WSMTemplatePath)
.Select(line => {
//TODO: having line check if we want to keep replacing
if (!doReplace || SomeCondition(line)) {
doReplace = false;
return line;
}
return MyReplace(line, dict)
}));
Here SomeCondition(line) returns true whenever header ends and we should not replace #..# any more.

How do I remove duplicates from excel range? c#

I've converted cells in my excel range from strings to form a string list and have separated each item after the comma in the original list. I am starting to think I have not actually separated each item, and they are still one whole, trying to figure out how to do this properly so that each item( ie. the_red_bucket_01)is it's own string.
example of original string in a cell 1 and 2:
Cell1 :
the_red_bucket_01, the_blue_duck_01,_the green_banana_02, the orange_bear_01
Cell2 :
the_purple_chair_01, the_blue_coyote_01,_the green_banana_02, the orange_bear_01
The new list looks like this, though I'm not sure they are separate items:
the_red_bucket_01
the_blue_duck_01
the green_banana_02
the orange_bear_01
the_red_chair_01
the_blue_coyote_01
the green_banana_02
the orange_bear_01
Now I want to remove duplicates so that the console only shows 1 of each item, no matter how many there are of them, I can't seem to get my foreah/if statements to work. It is printing out multiple copies of the items, I'm assuming because it is iterating for each item in the list, so it is returning the data that many items.
foreach (Excel.Range item in xlRng)
{
string itemString = (string)item.Text;
List<String> fn = new List<String>(itemString.Split(','));
List<string> newList = new List<string>();
foreach (string s in fn)
if (!newList.Contains(s))
{
newList.Add(s);
}
foreach (string combo in newList)
{
Console.Write(combo);
}
You probably need to trim the strings, because they have leading white spaces, so "string1" is different from " string1".
foreach (string s in fn)
if (!newList.Contains(s.Trim()))
{
newList.Add(s);
}
You can do this much simpler with Linq by using Distinct.
Returns distinct elements from a sequence by using the default
equality comparer to compare values.
foreach (Excel.Range item in xlRng)
{
string itemString = (string)item.Text;
List<String> fn = new List<String>(itemString.Split(','));
foreach (string combo in fn.Distinct())
{
Console.Write(combo);
}
}
As mentioned in another answer, you may also need to Trim any whitespace, in which case you would do:
fn.Select(x => x.Trim()).Distinct()
Where you need to contain keys/values, its better to use Dictionary type. Try changing code with List<T> to Dictionary<T>. i.e.
From:
List<string> newList = new List<string>();
foreach (string s in fn)
if (!newList.Containss))
{
newList.Add(s);
}
to
Dictionary<string, string> newList = new Dictionary<string, string>();
foreach (string s in fn)
if (!newList.ContainsKey(s))
{
newList.Add(s, s);
}
If you are concerned about the distinct items while you are reading, then just use the Distinct operator like fn.Distinct()
For processing the whole data, I can suggest two methods:
Read in the whole data then use LINQ's Distinct operator
Or use a Set data structure and store each element in that while reading the excel
I suggest that you take a look at the LINQ documentation if you are processing data. It has really great extensions. For even more methods, you can check out the MoreLINQ package.
I think your code would probably work as you expect if you moved newList out of the loop - you create a new variable named newList each loop so it's not going to find duplicates from earlier loops.
You can do all of this this more concisely with Linq:
//set up some similar data
string list1 = "a,b,c,d,a,f";
string list2 = "a,b,c,d,a,f";
List<string> lists = new List<string> {list1,list2};
// find unique items
var result = lists.SelectMany(i=>i.Split(',')).Distinct().ToList();
SelectMany() "flattens" the list of lists into a list.
Distinct() removes duplicates.
var uniqueItems = new HashSet<string>();
foreach (Excel.Range cell in xlRng)
{
var cellText = (string)cell.Text;
foreach (var item in cellText.Split(',').Select(s => s.Trim()))
{
uniqueItems.Add(item);
}
}
foreach (var item in uniqueItems)
{
Console.WriteLine(item);
}

Adding textfile string into specific list item

I have a text file that has a string like:
"•5•Enter Title Name•Enter Description Here•30/04/2015•UNFINISHED•"
I am reading this text file in, how can I write it so the items between the • are put in seperate variables or strings. I have a general idea, using foreach loops with an if statement that checks for the specific character. Can anybody help me please? (code so far is below)
MessageBox.Show("Opening saved file: TaskFile.txt");
string path1 = (#"TaskFile.txt");
string lineOfText = File.ReadAllText(path1);
System.Diagnostics.Debug.WriteLine(lineOfText);
foreach (var sItem in lineOfText)
{
if(sItem == '•')
{
System.Diagnostics.Debug.WriteLine("test");
}
}
You can use Split method and use it like this
List<string> list = sItem.Split('.').ToList();
I agree with Ehsan on the Split method, but I think it should be like this:
var arrayOfStrings = lineOfText.Split('•');
foreach (var str in arrayOfStrings)
{
//do something.
}

Stringbuilder add new line inside foreach loop

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

How to add string to an array list in c#

I have a list and a string
var Resnames= new List<string>();
string name = "something";
I want to append string to it like
Resnames += name;
How can I do it
Since you are using List (not a legacy fixed-size array) you able to use List.Add() method:
resourceNames.Add(name);
If you want to add an item after the instantiation of a list instance you can use object initialization (since C# 3.0):
var resourceNames = new List<string> { "something", "onemore" };
Also you might find useful List.AddRange() method as well
var resourceNames = new List<string>();
resourceNames.Add("Res1");
resourceNames.Add("Res2");
var otherNames = new List<string>();
otherNames.AddRange(resourceNames);
Just as simple as that:
Resnames.Add(name);
BTW: VisualStudio is your friend! By typing a . after Resnames it would have helped you.
try adding the string to array list like this,
var Resnames= new List<string>();
string name = "something";
Resnames.Add(name);
foreach (var item in Resnames)
{
Console.WriteLine(item);
}
Add String to List this way:
var ListName = new List<string>();
string StringName = "YourStringValue";
ListName.Add(StringName);

Categories

Resources