Let’s say you have a class like that: public class Student { public string Name { get; set; } public string Surname { get; set; } public DateTime DateCreated { get; set; } … } If you want to join the name values of that class then you can use the code below: using System.Linq […]
Category: C#
How to remove all non alphanumeric characters from a string in C#
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 = […]
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 get rows count in EntityFramework without loading contents
Query syntax: var count = (from t in context.MyTable where t.Id == @Id select t).Count(); Method syntax: var count = context.MyTable .Where(t => t.Id == @Id) .Count() Both generate the same SQL query.
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 difference between “int” and “uint” / “long” and “ulong”?
The primitive data types prefixed with “u” are unsigned versions with the same bit sizes. Effectively, this means they cannot store negative numbers, but on the other hand, they can store positive numbers twice as large as their signed counterparts. The signed counterparts do not have “u” prefixed. The limits for int (32-bit) are: […]
What is the difference between ‘ref’ and ‘out’ keywords in C#
The best way to understand that difference is to show it in code. Let’s say we have an ‘Add’ function. And the only thing that method does is add 10 to the parameter value. static void Main (string[] args) { int myParameter = 20; Add(myParameter); Console.WriteLine(myParameter); } static void Add(int myParameter) { myParameter = myParameter […]
What is the difference between HashSet and List in .net?
Unlike a List<> A HashSet is a List with no duplicate members. Because a HashSet is constrained to contain only unique entries, the internal structure is optimized for searching (compared with a list) – it is considerably faster Adding to a HashSet returns a boolean – false if addition fails due to already existing in […]
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 Conditional Operator in C# (?.)
The null conditional operator (?.) is colloquially referred to as the “Elvis operator” because of its resemblance to a pair of dark eyes under a large quiff of hair. The null conditional is a form of a member access operator (the .). Here’s a simplified explanation for the null conditional operator: The expression A?.B evaluates to B if the left operand (A) […]
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 […]
What is the difference between IQueryable and IEnumerable?
That StackOverflow answer so far is the best one I have ever seen: This is an excellent video on youtube which demonstrates how these interfaces differ, worth a watch. Below goes a long descriptive answer to it. The first important point to remember is IQueryable interface inherits from IEnumerable, so whatever IEnumerable can do, IQueryable can also do. There are many differences […]
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;