diff --git a/snippets/csharp/icon.svg b/snippets/csharp/icon.svg new file mode 100644 index 00000000..96cf5abc --- /dev/null +++ b/snippets/csharp/icon.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/snippets/csharp/list-utilities/swap-items-at-index.md b/snippets/csharp/list-utilities/swap-items-at-index.md new file mode 100644 index 00000000..4e8113a4 --- /dev/null +++ b/snippets/csharp/list-utilities/swap-items-at-index.md @@ -0,0 +1,28 @@ +--- +title: Swap two items at determined indexes +description: Swaps two items at determined indexes +author: omegaleo +tags: csharp,c#,list,utility +--- + +```csharp +/// +/// Swaps the position of 2 elements inside of a List +/// +/// List with swapped elements +public static IList Swap(this IList list, int indexA, int indexB) +{ + (list[indexA], list[indexB]) = (list[indexB], list[indexA]); + return list; +} + +var list = new List() {"Test", "Test2"}; + +Console.WriteLine(list[0]); // Outputs: Test +Console.WriteLine(list[1]); // Outputs: Test2 + +list = list.Swap(0, 1).ToList(); + +Console.WriteLine(list[0]); // Outputs: Test2 +Console.WriteLine(list[1]); // Outputs: Test +``` diff --git a/snippets/csharp/string-utilities/truncate-string.md b/snippets/csharp/string-utilities/truncate-string.md new file mode 100644 index 00000000..5213bed4 --- /dev/null +++ b/snippets/csharp/string-utilities/truncate-string.md @@ -0,0 +1,21 @@ +--- +title: Truncate a String +description: Cut off a string once it reaches a determined amount of characters and add '...' to the end of the string +author: omegaleo +tags: csharp,c#,list,utility +--- + +```csharp +/// +/// Cut off a string once it reaches a amount of characters and add '...' to the end of the string +/// +public static string Truncate(this string value, int maxChars) +{ + return value.Length <= maxChars ? value : value.Substring(0, maxChars) + "..."; +} + +var str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam tristique rhoncus bibendum. Vivamus laoreet tortor vel neque lacinia, nec rhoncus ligula pellentesque. Nullam eu ornare nibh. Donec tincidunt viverra nulla."; + +Console.WriteLine(str); // Outputs the full string +Console.WriteLine(str.Truncate(5)); // Outputs Lorem... +```