Skip to content

Added some C# snippets #98

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jan 1, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions snippets/csharp/icon.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
28 changes: 28 additions & 0 deletions snippets/csharp/list-utilities/swap-items-at-index.md
Original file line number Diff line number Diff line change
@@ -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
/// <summary>
/// Swaps the position of 2 elements inside of a List
/// </summary>
/// <returns>List with swapped elements</returns>
public static IList<T> Swap<T>(this IList<T> list, int indexA, int indexB)
{
(list[indexA], list[indexB]) = (list[indexB], list[indexA]);
return list;
}

var list = new List<string>() {"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
```
21 changes: 21 additions & 0 deletions snippets/csharp/string-utilities/truncate-string.md
Original file line number Diff line number Diff line change
@@ -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
/// <summary>
/// Cut off a string once it reaches a <paramref name="maxChars"/> amount of characters and add '...' to the end of the string
/// </summary>
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...
```
Loading