Skip to content
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

Add more string array extensions #1

Merged
merged 3 commits into from
Oct 10, 2023
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
2 changes: 1 addition & 1 deletion src/ArrayExtensions/ArrayExtensions.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
<PackageTags>array, extensions</PackageTags>
<PackageLicenseFile>LICENSE.txt</PackageLicenseFile>
<PackageReadmeFile>README.md</PackageReadmeFile>
<Version>1.2</Version>
<Version>1.2.1</Version>
<EnablePackageValidation>true</EnablePackageValidation>
<PackageLicenseFile>LICENSE.txt</PackageLicenseFile>
<PackageReadmeFile>README.md</PackageReadmeFile>
Expand Down
98 changes: 91 additions & 7 deletions src/ArrayExtensions/Extensions/StringArrayExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,48 +7,132 @@
/// </summary>
/// <param name="arr">The array to check.</param>
/// <returns>True if atleast one item is null or empty.</returns>
public static bool AnyNullOrEmpty(this string[] arr) => arr.Any(string.IsNullOrEmpty);
public static bool AnyNullOrEmpty(this string[] arr)
=> arr.Any(string.IsNullOrEmpty);

/// <summary>
/// Checks if any item is null or whitespace in the array.
/// </summary>
/// <param name="arr">The array to check.</param>
/// <returns>True if atleast one item is null or empty.</returns>
public static bool AnyNullOrWhiteSpace(this string[] arr) => arr.Any(string.IsNullOrWhiteSpace);
public static bool AnyNullOrWhiteSpace(this string[] arr)
=> arr.Any(string.IsNullOrWhiteSpace);

/// <summary>
/// Trims all items in the array
/// </summary>
/// <param name="arr">The array to trim all items.</param>
/// <returns>Array with trimmed items.</returns>
public static string[] TrimAll(this string[] arr) => arr.Select(s => s.Trim()).ToArray();
public static string[] TrimAll(this string[] arr)
=> arr.Select(s => s.Trim()).ToArray();

/// <summary>
/// Removes all empty and null items from the array.
/// </summary>
/// <param name="arr">The array to remove null or empty items from.</param>
/// <returns>Array without null or empty values.</returns>
public static string[] RemoveNullOrEmpty(this string[] arr) => arr.Where(s => !string.IsNullOrEmpty(s)).ToArray();
public static string[] RemoveNullOrEmpty(this string[] arr)
=> arr.Where(s => !string.IsNullOrEmpty(s)).ToArray();

/// <summary>
/// Removes all whitespace and null items from the array.
/// </summary>
/// <param name="arr">The array to remove whitespace or empty items from.</param>
/// <returns>Array without null or empty values.</returns>
public static string[] RemoveNullOrWhiteSpace(this string[] arr) => arr.Where(s => !string.IsNullOrWhiteSpace(s)).ToArray();
public static string[] RemoveNullOrWhiteSpace(this string[] arr)
=> arr.Where(s => !string.IsNullOrWhiteSpace(s)).ToArray();

/// <summary>
/// Checks if the array has duplicate values.
/// </summary>
/// <param name="arr">The array to check.</param>
/// <returns>True if any duplicate values present.</returns>
public static bool HasDuplicates(this string[] arr) => arr.GroupBy(s => s).Any(g => g.Count() > 1);
public static bool HasDuplicates(this string[] arr)
=> arr.GroupBy(s => s).Any(g => g.Count() > 1);

/// <summary>
/// Concatenate all strings with a given separator.
/// </summary>
/// <param name="arr">The array to concatenate.</param>
/// <param name="separator">The separator.</param>
/// <returns>Concatenated string from all array elements.</returns>
public static string ConcatenateWithSeparator(this string[] arr, string separator) => string.Join(separator, arr);
public static string ConcatenateWithSeparator(this string[] arr, string separator)
=> string.Join(separator, arr);

/// <summary>
/// Converts all strings in the array to uppercase.
/// </summary>
/// <param name="arr">The array to convert.</param>
/// <returns>Array with all uppercase strings.</returns>
public static string[] ToUpperCase(this string[] arr)
=> arr.Select(s => s.ToUpper()).ToArray();

/// <summary>
/// Converts all strings in the array to lowercase.
/// </summary>
/// <param name="arr">The array to convert.</param>
/// <returns>Array with all lowercase strings.</returns>
public static string[] ToLowerCase(this string[] arr)
=> arr.Select(s => s.ToLower()).ToArray();

/// <summary>
/// Reverses each string in the array.
/// </summary>
/// <param name="arr">The array to reverse.</param>
/// <returns>Array with reversed strings.</returns>
public static string[] ReverseEach(this string[] arr)
=> arr.Select(s => new string(s.Reverse().ToArray())).ToArray();

/// <summary>
/// Filters strings that match a given pattern.
/// </summary>
/// <param name="arr">The array to filter.</param>
/// <param name="pattern">The pattern to match.</param>
/// <returns>Array with strings that match the pattern.</returns>
public static string[] FilterByPattern(this string[] arr, string pattern)
=> arr.Where(s => System.Text.RegularExpressions.Regex.IsMatch(s, pattern)).ToArray();

/// <summary>
/// Counts occurrences of a substring in all strings of the array.
/// </summary>
/// <param name="arr">The array to check.</param>
/// <param name="substring">The substring to count.</param>
/// <returns>Total occurrences of the substring.</returns>
public static int CountOccurrencesOfSubstring(this string[] arr, string substring)
=> arr.Sum(s => s.Split(new[] { substring }, StringSplitOptions.None).Length - 1);

/// <summary>
/// Replaces a substring in all strings of the array.
/// </summary>
/// <param name="arr">The array to replace in.</param>
/// <param name="oldValue">The old substring.</param>
/// <param name="newValue">The new substring.</param>
/// <returns>Array with replaced substrings.</returns>
public static string[] ReplaceInAll(this string[] arr, string oldValue, string newValue)
=> arr.Select(s => s.Replace(oldValue, newValue)).ToArray();

/// <summary>
/// Checks if all strings in the array are of a certain length.
/// </summary>
/// <param name="arr">The array to check.</param>
/// <param name="length">The length to check.</param>
/// <returns>True if all strings have the specified length.</returns>
public static bool AllOfLength(this string[] arr, int length)
=> arr.All(s => s.Length == length);

/// <summary>
/// Gets the longest string from the array.
/// </summary>
/// <param name="arr">The array to check.</param>
/// <returns>The longest string.</returns>
public static string LongestString(this string[] arr)
=> arr.OrderByDescending(s => s.Length).FirstOrDefault();

Check warning on line 129 in src/ArrayExtensions/Extensions/StringArrayExtensions.cs

View workflow job for this annotation

GitHub Actions / create_nuget

Possible null reference return.

Check warning on line 129 in src/ArrayExtensions/Extensions/StringArrayExtensions.cs

View workflow job for this annotation

GitHub Actions / run_test

Possible null reference return.

/// <summary>
/// Gets the shortest string from the array.
/// </summary>
/// <param name="arr">The array to check.</param>
/// <returns>The shortest string.</returns>
public static string ShortestString(this string[] arr)
=> arr.OrderBy(s => s.Length).FirstOrDefault();

Check warning on line 137 in src/ArrayExtensions/Extensions/StringArrayExtensions.cs

View workflow job for this annotation

GitHub Actions / create_nuget

Possible null reference return.

Check warning on line 137 in src/ArrayExtensions/Extensions/StringArrayExtensions.cs

View workflow job for this annotation

GitHub Actions / run_test

Possible null reference return.
}
13 changes: 12 additions & 1 deletion src/ArrayExtensions/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ A collection of useful extension methods for arrays in C#.
- **Basic Operations**: Easily `Add`, `Insert`, `Remove`, and `Replace` items.
- **Array Manipulation**: `Shuffle`, `Rotate`, `Chunk`, `Flatten`, and `Resize` your arrays.
- **Array Analysis**: Check if arrays are `AllEqual`, `AnyNull`, `IsEmpty`, or even find the `MostCommon` element.
- **String Array Utilities**: Methods like `TrimAll`, `AnyNullOrEmpty`, and `ConcatenateWithSeparator`.
- **String Array Utilities**: Methods like `TrimAll`, `AnyNullOrEmpty`, `ConcatenateWithSeparator` and filters.
- **DateTime Array Utilities**: Filter by `Weekdays`, `Weekends`, `Holidays`, and more.
- **Safe Operations**: Safely `Get`, `Set`, and `FindIndices` without worrying about out-of-range errors.
- **Functional Programming**: Use `ForEach` to apply actions directly on array elements.
Expand Down Expand Up @@ -46,6 +46,17 @@ bool hasEmptyOrNull = fruits.AnyNullOrEmpty();
// String utilities
string[] trimmedFruits = { " apple ", "banana ", " cherry", " date " };
trimmedFruits = trimmedFruits.TrimAll();
fruitsWithValues = fruitsWithValues.RemoveNullOrEmpty(); // Removes empty and null values, resulting in { "apple", "cherry" }

string[] fruitsWithSpaces = { "apple", " ", "cherry", null };
fruitsWithSpaces = fruitsWithSpaces.RemoveNullOrWhiteSpace(); // Removes whitespace-only and null values, resulting in { "apple", "cherry" }

bool hasDuplicateFruits = fruits.HasDuplicates(); // Checks if there are any duplicate fruit names
string fruitSentence = fruits.ConcatenateWithSeparator(", "); // Joins all fruit names with a comma separator
string[] fruitsWithPattern = fruits.FilterByPattern("^a.*"); // Filters fruits that start with the letter 'a'
bool allOfLengthFive = fruits.AllOfLength(5); // Checks if all fruit names have a length of 5
string longestFruit = fruits.LongestString(); // Gets the longest fruit name
string shortestFruit = fruits.ShortestString(); // Gets the shortest fruit name

// DateTime utilities
DateTime[] holidays = { new DateTime(2023, 12, 25), new DateTime(2023, 1, 1) };
Expand Down
Loading