Linger.Utils 0.7.2

dotnet add package Linger.Utils --version 0.7.2
                    
NuGet\Install-Package Linger.Utils -Version 0.7.2
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Linger.Utils" Version="0.7.2" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Linger.Utils" Version="0.7.2" />
                    
Directory.Packages.props
<PackageReference Include="Linger.Utils" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Linger.Utils --version 0.7.2
                    
#r "nuget: Linger.Utils, 0.7.2"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Linger.Utils@0.7.2
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Linger.Utils&version=0.7.2
                    
Install as a Cake Addin
#tool nuget:?package=Linger.Utils&version=0.7.2
                    
Install as a Cake Tool

Linger.Utils

πŸ“ View this document in: English | δΈ­ζ–‡

A comprehensive .NET utility library providing extensive type conversion extensions, string manipulation utilities, date/time helpers, file system operations, collection extensions, and various helper classes for everyday development tasks.

Overview

Linger.Utils offer a rich collection of extension methods and helper classes that make common programming tasks simpler and more efficient. The library follows modern C# coding practices and supports multiple .NET framework versions.

Table of Contents

Features

πŸš€ Core Extensions

  • String Extensions: Rich string operations, validation, conversion, and formatting utilities
  • DateTime Extensions: Date and time manipulation, formatting, and calculations
  • Numeric Extensions: Type-safe numeric conversions and operations
  • Enum Extensions: Enhanced enum handling and conversion
  • Object Extensions: General object operations and validation
  • Array Extensions: Array processing and manipulation utilities
  • GUID Extensions: GUID operation and validation utilities

πŸ“¦ Collection Extensions

  • List Extensions: Enhanced list operations and processing
  • Collection Extensions: General collection utilities and transformations

πŸ’Ύ Data Extensions

  • DataTable Extensions: DataTable operation utilities
  • Data Conversion: Safe data type conversion and transformation

πŸ“ File System Operations

  • File Helper: Comprehensive file operations (read, write, copy, move, delete)
  • Path Helper: Cross-platform path operations and validation
  • Directory Operations: Directory management and traversal utilities

πŸ”§ Helper Classes

  • Expression Helper: Expression tree operations and utilities
  • Retry Helper: Robust retry mechanisms for operations
  • Property Helper: Reflection-based property operations
  • GUID Code: Enhanced GUID generation and operations
  • OS Platform Helper: Cross-platform operating system detection
  • Parameter Validation Extensions: Defensive programming and input validation utilities

🌐 JSON Support

  • JSON Extensions: Simplified JSON serialization and deserialization
  • Custom Converters: Specialized JSON converters for complex types

Installation

dotnet add package Linger.Utils

Target Frameworks

  • .NET 9.0
  • .NET 8.0
  • .NET Standard 2.0
  • .NET Framework 4.7.2

Quick Start

String Extensions

using Linger.Extensions.Core;

// String validation
string email = "user@example.com";
bool isValid = email.IsEmail();

// String conversion
string number = "123";
int result = number.ToInt(0); // Returns 123, or 0 if conversion fails
int? nullableResult = number.ToIntOrNull(); // Returns nullable type

// String manipulation
string text = "  Hello World  ";
string cleaned = text.Trim(); // Removes whitespace from both ends (.NET native method)

// String extraction
string longText = "Hello World";
string leftPart = longText.Left(5); // Get left 5 characters: Hello
string rightPart = longText.Right(5); // Get right 5 characters: World
string part = longText.SafeSubstring(0, 20); // Won't throw if length exceeds

// String checks
bool isEmpty = text.IsNullOrEmpty();
bool isNumber = number.IsNumber(); // Check if it's a number
bool isInt = number.IsInteger(); // Check if it's an integer

DateTime Extensions

using Linger.Extensions.Core;

DateTime date = DateTime.Now;

// Age calculation
DateTime birthDate = new DateTime(1990, 5, 15);
int age = birthDate.CalculateAge();

// Date range operations
bool isInRange = date.InRange(DateTime.Today, DateTime.Today.AddDays(7));

// Date operations
DateTime startOfDay = date.StartOfDay(); // Beginning of the day
DateTime endOfDay = date.EndOfDay(); // End of the day
DateTime startOfMonth = date.StartOfMonth(); // Beginning of the month
DateTime endOfMonth = date.EndOfMonth(); // End of the month

File Operations

using Linger.Helper;

// File operations
FileHelper.WriteText("data.txt", "Hello World");
string content = FileHelper.ReadText("data.txt");

// File copy with directory creation
FileHelper.CopyFile("source.txt", "backup/dest.txt");

// Safe file deletion
FileHelper.DeleteFileIfExists("temp.txt");

// Directory operations
FileHelper.EnsureDirectoryExists("logs/2024");

Collection Extensions

using Linger.Extensions.Collection;

var list = new List<int> { 1, 2, 3, 4, 5 };

// Safe collection state checking
bool isEmpty = list.IsNullOrEmpty(); // Check if null or empty

// Pagination
var pagedResult = list.Paging(2, 2); // Page 2, 2 items per page: [3, 4]

// Convert to delimited string
string result = list.ToSeparatedString(", "); // "1, 2, 3, 4, 5"

// Execute action on each element
list.ForEach(Console.WriteLine); // Print each element

// Convert to DataTable
var dataTable = list.Select(x => new { Value = x }).ToDataTable();

Object Extensions

using Linger.Extensions.Core;

// Null-safe operations
object obj = GetSomeObject();
string result = obj.ToSafeString("default");

// Type checking
string stringValue = obj.ToString(); // .NET native method
bool isNumber = stringValue.IsNumber();
bool isInt = stringValue.IsInteger();
bool isDouble = stringValue.IsDouble();

// Object conversion
var stringRepresentation = obj.ToStringOrNull();

// Range checking (for numeric values)
int value = 5;
bool inRange = value.InRange(1, 10); // Check if in range

JSON Extensions

using Linger.Extensions;

// Object to JSON
var user = new { Name = "John", Age = 30 };
string json = user.ToJsonString(); // or user.SerializeJson()

// JSON to object
var userObj = json.Deserialize<User>(); // or json.DeserializeJson<User>()

// Dynamic JSON object
dynamic dynamicObj = json.DeserializeDynamicJsonObject();
string name = dynamicObj.Name; // Access properties

// JSON to DataTable (string extension)
string jsonArray = "[{\"Name\":\"John\",\"Age\":30}]";
DataTable? dataTable = jsonArray.ToDataTable();

GUID Extensions

using Linger.Extensions.Core;

// GUID checking
Guid guid = Guid.NewGuid();
bool isEmpty = guid.IsEmpty(); // Check if empty GUID
bool isNotEmpty = guid.IsNotEmpty(); // Check if not empty

// Nullable GUID operations
Guid? nullableGuid = null;
bool isNull = nullableGuid.IsNull(); // Check if null
bool isNotNull = nullableGuid.IsNotNull(); // Check if not null
bool isNullOrEmpty = nullableGuid.IsNullOrEmpty(); // Check if null or empty
bool isNotNullAndEmpty = nullableGuid.IsNotNullAndEmpty(); // Check if neither null nor empty

// GUID conversion
long longValue = guid.ToInt64(); // Convert to Int64
int intValue = guid.ToInt32(); // Convert to Int32

// .NET 9+ feature: V7 GUID timestamp extraction
#if NET9_0_OR_GREATER
DateTimeOffset timestamp = guid.GetTimestamp(); // Only for V7 GUIDs
#endif

Array Extensions

using Linger.Extensions.Core;

int[] numbers = { 1, 2, 3, 4, 5 };

// Execute action on each element
numbers.ForEach(n => Console.WriteLine(n)); // Output: 1 2 3 4 5

// Iterate with index
numbers.ForEach((n, index) => Console.WriteLine($"Index {index}: {n}"));
// Output: Index 0: 1, Index 1: 2, ...

Enum Extensions

using Linger.Extensions.Core;

public enum Status
{
    Active = 1,
    Inactive = 2,
    Pending = 3
}

// String to enum
string statusName = "Active";
Status status = statusName.GetEnum<Status>(); // or statusName.ToEnum<Status>()

// Integer to enum
int statusValue = 1;
Status statusFromInt = statusValue.GetEnum<Status>();

// Get enum name
string enumName = statusValue.GetEnumName<Status>(); // Returns "Active"

// Get enum description (if Description attribute exists)
string description = status.GetDescription(); // Get description text

Parameter Validation

using Linger.Helper;

public void ProcessData(string data, IEnumerable<int> numbers, string filePath)
{
    // Basic validation
    data.EnsureIsNotNull(nameof(data)); // Ensure not null
    data.EnsureIsNotNullAndEmpty(nameof(data)); // Ensure not null or empty
    data.EnsureIsNotNullAndWhiteSpace(nameof(data)); // Ensure not null, empty or whitespace

    // Collection validation
    numbers.EnsureIsNotNullOrEmpty(nameof(numbers)); // Ensure collection is not null or empty

    // File system validation
    filePath.EnsureFileExist(nameof(filePath)); // Ensure file exists
    Path.GetDirectoryName(filePath).EnsureDirectoryExist(); // Ensure directory exists

    // Condition validation
    (data.Length > 0).EnsureIsTrue(nameof(data), "Data must not be empty");
    (numbers.Count() < 1000).EnsureIsTrue(nameof(numbers), "Too many items");

    // Range validation
    int value = 5;
    value.EnsureIsInRange(1, 10, nameof(value)); // Ensure value is in range

    // Null checking
    object? obj = GetSomeObject();
    obj.EnsureIsNotNull(nameof(obj)); // If object should not be null
    // or
    obj.EnsureIsNull(nameof(obj)); // If object should be null
}

Advanced Features

Retry Helper

using Linger.Helper;

// Retry operation with configurable policy
var options = new RetryOptions 
{
    MaxRetries = 3,
    BaseDelayMs = 1000 // 1 second
};
var retryHelper = new RetryHelper(options);
var result = await retryHelper.ExecuteAsync(
    async () => await SomeOperationThatMightFail(),
    "Operation Name"
);

// Or use default options
var defaultRetryHelper = new RetryHelper();
var result2 = await defaultRetryHelper.ExecuteAsync(
    async () => await AnotherOperationThatMightFail(),
    "Another Operation Name"
);

Expression Helper

using Linger.Helper;
using Linger.Enums;

// Dynamic expression building
// Basic expressions
Expression<Func<User, bool>> trueExpression = ExpressionHelper.True<User>();
Expression<Func<User, bool>> falseExpression = ExpressionHelper.False<User>();

// Single condition expressions
Expression<Func<User, bool>> ageFilter = ExpressionHelper.CreateGreaterThan<User>("Age", "18");
Expression<Func<User, bool>> nameFilter = ExpressionHelper.GetContains<User>("Name", "John");

// Build complex expressions using condition collections
var conditions = new List<Condition>
{
    new Condition { Field = "Age", Op = CompareOperator.GreaterThan, Value = 18 },
    new Condition { Field = "Name", Op = CompareOperator.Contains, Value = "John" }
};
Expression<Func<User, bool>> complexFilter = ExpressionHelper.BuildLambda<User>(conditions);

Path Operations

using Linger.Helper.PathHelpers;

// Path normalization - handles relative paths, duplicate separators, etc.
string messyPath = @"C:\temp\..\folder\.\file.txt";
string normalized = StandardPathHelper.NormalizePath(messyPath);
// Result: "C:\folder\file.txt" (Windows) or "/folder/file.txt" (Unix)

// Path comparison - cross-platform safe path equality check
string path1 = @"C:\Users\Documents\file.txt";
string path2 = @"c:\users\documents\FILE.TXT"; // Different case
bool pathEquals = StandardPathHelper.PathEquals(path1, path2); // Windows: true, Linux: false

// Get relative path - from base path to target path
string basePath = @"C:\Projects\MyApp";
string targetPath = @"C:\Projects\MyApp\src\Components\Button.cs";
string relative = StandardPathHelper.GetRelativePath(basePath, targetPath);
// Result: "src\Components\Button.cs" (Windows) or "src/Components/Button.cs" (Unix)

// Resolve absolute path - convert relative path to absolute
string workingDir = @"C:\Projects";
string relativePath = @"MyApp\src\file.txt";
string absolutePath = StandardPathHelper.ResolveToAbsolutePath(workingDir, relativePath);
// Result: "C:\Projects\MyApp\src\file.txt"

// Check for invalid path characters
string suspiciousPath = "file<name>.txt"; // Contains invalid character '<'
bool hasInvalidChars = StandardPathHelper.ContainsInvalidPathChars(suspiciousPath); // true

// Check if file or directory exists
string filePath = @"C:\temp\data.txt";
bool fileExists = StandardPathHelper.Exists(filePath, checkAsFile: true); // Check as file
bool dirExists = StandardPathHelper.Exists(filePath, checkAsFile: false); // Check as directory

// Get parent directory path
string deepPath = @"C:\Projects\MyApp\src\Components\Button.cs";
string parentDir = StandardPathHelper.GetParentDirectory(deepPath, levels: 1);
// Result: "C:\Projects\MyApp\src\Components"
string grandParentDir = StandardPathHelper.GetParentDirectory(deepPath, levels: 2);
// Result: "C:\Projects\MyApp\src"

Best Practices

  1. Use Safe Methods: Prefer ToIntOrNull() over ToInt() when conversion might fail
  2. Null Checking: Use extension methods like IsNullOrEmpty() for validation
  3. Parameter Validation: Use GuardExtensions methods like EnsureIsNotNull(), EnsureIsNotNullAndEmpty() for input validation
  4. Leverage Async: Use async versions of file operations for better performance
  5. Error Handling: Always handle potential exceptions in file operations
  6. Resource Management: Use using statements for disposable resources
  7. GUID Operations: Use extension methods like IsEmpty() and IsNotEmpty() instead of direct comparison
  8. Collection Processing: Use ForEach() extension methods to simplify array and collection iteration

Dependencies

The library has minimal external dependencies:

  • System.Text.Json (for JSON operations)
  • System.Data.DataSetExtensions (for .NET Framework and .NET Standard 2.0)

Contributing

Contributions are welcome! Please feel free to submit a Pull Request. Please ensure:

  • Follow existing code style
  • Add unit tests for new features
  • Update documentation as needed

License

This project is licensed under the terms of the license provided with the Linger project.


For more information about the Linger framework and other related packages, visit the Linger Project Repository.

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 is compatible.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (19)

Showing the top 5 NuGet packages that depend on Linger.Utils:

Package Downloads
Linger.FileSystem

Unified file system abstraction library that provides a consistent interface for accessing different file systems (local, FTP, SFTP). Core library containing the base interfaces, models, and local file system implementation.

Linger.Configuration

A lightweight configuration helper library for .NET applications. Simplifies access to application settings with strongly-typed configuration binding. Provides utilities for working with appsettings.json and other configuration sources.

Linger.EFCore

An Entity Framework Core extension library providing enhanced capabilities. Includes global query filters, property conversions for complex types, and pagination utilities. Simplifies working with JSON data, collections, and complex filtering scenarios.

Linger.Email

A C# email helper library that provides simplified email operations, SMTP support, HTML and plain text emails, attachment handling, and asynchronous sending capabilities. Built on top of MailKit for robust and secure email communication across multiple .NET frameworks.

Linger.SharedKernel

Core domain primitives and shared components for Linger applications. Provides base search models, pagination support, and essential building blocks for implementing domain-driven design patterns across multiple projects.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.7.2 391 6/3/2025
0.7.1 394 5/21/2025
0.7.0 402 5/19/2025
0.6.0-alpha 393 4/28/2025
0.5.0-alpha 402 4/10/2025
0.4.0-alpha 386 4/1/2025
0.3.3-alpha 360 3/19/2025
0.3.2-alpha 356 3/17/2025
0.3.1-alpha 325 3/16/2025
0.3.0-alpha 395 3/6/2025
0.2.0-alpha 235 2/9/2025
0.1.2-alpha 152 12/17/2024
0.1.1-alpha 146 12/17/2024
0.1.0-alpha 218 12/6/2024
0.0.9-alpha 131 11/27/2024
0.0.8-alpha 105 10/21/2024
0.0.7-alpha 97 10/12/2024
0.0.6-alpha 93 10/12/2024
0.0.5-alpha 89 10/7/2024
0.0.4-alpha 135 10/3/2024
0.0.3-alpha 198 8/9/2024
0.0.2-alpha 124 8/9/2024
0.0.1-alpha 123 7/22/2024