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: C#
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 if else block to decide style in Razor
Declare a local variable at the beginning of the View: @{ var yourStyle = “”; if(Model.Condition) { yourStyle = “float:left;”; //specific conditions and logic } else { yourStyle = “float:right;”; //any other conditions and logic } } and then just use it in your div: <div style=”@yourStyle”>
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 […]
String Interpolation, String Format, String Concat and String Builder in C#
We will try to return a string like: “I can text whatever I want with 4 different options in C#. ” with String Interpolation, String Format, String Concat, and String Builder. public class StringOptions { private string data1 = “4”; private string data2 = “C#”; public string StringInterpolation() => ($”I can text whatever I want […]
How to get value from resx file in C#
// Gets the value of associated with key “MyKey” from the local resource file (“~/MyPage.aspx.en.resx”) or from the default one (“~/MyPage.aspx.resx”) //The default location for resx files is App_LocalResources object keyValue = HttpContext.GetLocalResourceObject(“~/MyPage.aspx”, “MyKey”);
How to lock the ciritical code part in C#
According to Microsoft: The lock keyword ensures that one thread does not enter a critical section of code while another thread is in the critical section. If another thread tries to enter a locked code, it will wait, block, until the object is released. The lock keyword calls Enter at the start of the block and Exit at the end of the block. lock keyword actually […]
How to use SQL RAISEERROR() messages in C#
DECLARE @MyValue int SELECT @MyValue = Column1 WHERE Column2 > 50 IF @MyValue IS NULL BEGIN RAISEERROR(‘This is my custom message from SQL.’, 16, 1) END ELSE SELECT MyValue END Use an error code within 11-16, or just use 16 for a “general” case. RAISERROR(‘This is my custom message from SQL.’,16,1) Why? Here’s summary of […]
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: […]