Replace [^a-zA-Z0-9] with an empty string. string str = “This-is-my+++***RegexPattern&Text”; Regex rgx = new Regex(“[^a-zA-Z0-9]”); str = rgx.Replace(str, “”); OUTPUT: ThisismyRegexPatternText If you want to add an exception then you should add this character like this to the regex pattern (let’s assume you wish to exclude the ampersand): [^a-zA-Z0-9 &] string str = “This-is-my+++***RegexPattern&Text”; Regex rgx = […]
Tag: csharp
How to get the Xth Day of the Week of the Year in C#
Let’s say we want to find the date of the first Friday of the 1st month. GetFirstFridayOfMonth(01.01.2023) =>06.01.2023 (The first Friday after 01.01.2023 is 06.01.2023) public DateTime GetFirstFridayOfMonth(DateTime date) { DateTime fridayDate = new DateTime(date.Year, date.Month, 1); //Let’s assume 1st Friday can start on the 1st of the month while (fridayDate.DayOfWeek != DayOfWeek.Friday) { fridayDate […]
How to get formatted JSON in C#
Like converting XML to Json or Json to XML, you can also use Newtonsoft to get formatted Json. private static string FormatJson(string json) { dynamic parsedJson = JsonConvert.DeserializeObject(json); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } Note: You can use var instead of dynamic. Both will work.
How to convert JSON to XML or XML to JSON in C#
To do that easily, you can use Newtonsoft. // To convert an XML node contained in string xml into a JSON string XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); string jsonText = JsonConvert.SerializeXmlNode(doc); // To convert JSON text contained in string json into an XML node XmlDocument doc = JsonConvert.DeserializeXmlNode(json); You can get more info from […]
How to use TrimEnd to remove last character from string in C#
string useOfTrimEnd1= “Hello World !”.TrimEnd(‘!’); OUTPUT: Hello World string useOfTrimEnd2= “Hello World !!!!!!”.TrimEnd(‘!’); OUTPUT: Hello World Definition from Microsoft.com: TrimEnd(Char) Removes all the trailing occurrences of a character from the current string. TrimEnd() Removes all the trailing white-space characters from the current string. TrimEnd(Char[]) Removes all the trailing occurrences of a set of characters specified […]
What is the purpose of nameof in C#?
The purpose of nameof is refactoring. For example, when you change the name of a class to which you refer through nameof somewhere else in your code you will get a compilation error which is what you want. If you didn’t use nameof and had just a plain string as a reference you’d have to full-text […]
What is the difference between Select and SelectMany in Linq
The formal description for SelectMany() is: Projects each element of a sequence to an IEnumerable and flattens the resulting sequences into one sequence. SelectMany() flattens the resulting sequences into one sequence and invokes a result selector function on each element. The main difference is the result of each method while SelectMany() returns flattened results; Select() […]
The Ternary Operator in C# (?:)
C# includes a decision-making operator ?: called the conditional operator or ternary operator. It is the short form of the if-else conditions. Syntax: condition ? statement 1 : statement 2 The ternary operator starts with a boolean condition. If this condition evaluates to true then it will execute the first statement after ?, otherwise the second statement after : will […]
The Null-Coalescing Operators in C# (?? and ??=)
The null-coalescing operator ?? returns the value of its left-hand operand if it isn’t null; otherwise, it evaluates the right-hand operand and returns its result. The ?? operator doesn’t evaluate its right-hand operand if the left-hand operand evaluates to non-null. int? myValue = null; int result = myValue ?? -1; //result = -1; Syntax: p ?? q Here, p is […]
Understanding Stack and Heap
When you declare a variable in a .NET application, it allocates some chunk of memory in the RAM. This memory has three things: the name of the variable, the data type of the variable, and the value of the variable. That was a simple explanation of what happens in the memory, but depending on the […]
How to calculate difference (number of days) between two dates in C#
Let’s say we haveStartDate and EndDate and those are of type DateTime. If you want to have an int value as a result then: int theResult = (EndDate – StartDate).Days; And if you want to have a double value as a result then: double theResult = (EndDate – StartDate).TotalDays;
Constructor for a static class in C#
C# has a static constructor for this purpose. static class YourClass { static YourClass() { // perform initialization here } } A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or […]
IndexOf() and LastIndexOf() in C#
The IndexOf() method returns the index number of the first matched character whereas the LastIndexOf() method returns the index number of the last matched character. using System; public class StringExample { public static void Main(string[] args) { string s1 = “Hello C#”; int first = s1.IndexOf(‘l’); int last = s1.LastIndexOf(‘l’); Console.WriteLine(first); Console.WriteLine(last); } } Output: […]