Skip to content

Commit 9708e53

Browse files
Merge pull request #98 from omegaleo/feature/csharp-snippets
Added some C# snippets
2 parents 5af6825 + 3ca85eb commit 9708e53

File tree

3 files changed

+59
-0
lines changed

3 files changed

+59
-0
lines changed

snippets/csharp/icon.svg

Lines changed: 10 additions & 0 deletions
Loading
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
---
2+
title: Swap two items at determined indexes
3+
description: Swaps two items at determined indexes
4+
author: omegaleo
5+
tags: csharp,c#,list,utility
6+
---
7+
8+
```csharp
9+
/// <summary>
10+
/// Swaps the position of 2 elements inside of a List
11+
/// </summary>
12+
/// <returns>List with swapped elements</returns>
13+
public static IList<T> Swap<T>(this IList<T> list, int indexA, int indexB)
14+
{
15+
(list[indexA], list[indexB]) = (list[indexB], list[indexA]);
16+
return list;
17+
}
18+
19+
var list = new List<string>() {"Test", "Test2"};
20+
21+
Console.WriteLine(list[0]); // Outputs: Test
22+
Console.WriteLine(list[1]); // Outputs: Test2
23+
24+
list = list.Swap(0, 1).ToList();
25+
26+
Console.WriteLine(list[0]); // Outputs: Test2
27+
Console.WriteLine(list[1]); // Outputs: Test
28+
```
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
---
2+
title: Truncate a String
3+
description: Cut off a string once it reaches a determined amount of characters and add '...' to the end of the string
4+
author: omegaleo
5+
tags: csharp,c#,list,utility
6+
---
7+
8+
```csharp
9+
/// <summary>
10+
/// Cut off a string once it reaches a <paramref name="maxChars"/> amount of characters and add '...' to the end of the string
11+
/// </summary>
12+
public static string Truncate(this string value, int maxChars)
13+
{
14+
return value.Length <= maxChars ? value : value.Substring(0, maxChars) + "...";
15+
}
16+
17+
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.";
18+
19+
Console.WriteLine(str); // Outputs the full string
20+
Console.WriteLine(str.Truncate(5)); // Outputs Lorem...
21+
```

0 commit comments

Comments
 (0)