Search Results for

    Show / Hide Table of Contents

    Class MiscExtensions

    A set of miscellaneous extension and helper methods

    Inheritance
    object
    MiscExtensions
    Inherited Members
    object.GetType()
    object.MemberwiseClone()
    object.ToString()
    object.Equals(object)
    object.Equals(object, object)
    object.ReferenceEquals(object, object)
    object.GetHashCode()
    Namespace: LemonEdge.Utils
    Assembly: LemonEdge.Utils.dll
    Syntax
    public static class MiscExtensions

    Methods

    AddIgnoringNulls<T>(IList<T>, T)

    Adds the item to the list as long as it is not null

    Declaration
    public static void AddIgnoringNulls<T>(this IList<T> items, T item)
    Parameters
    Type Name Description
    IList<T> items

    The list of items to add a single item to

    T item

    The item to add to the list as long as it is not null

    Type Parameters
    Name Description
    T

    The type of items in the list

    AddOrUpdate<K, T>(IDictionary<K, T>, K, Func<Task<T>>, Func<K, T, T>)

    Adds the specified item to the dictionary, or if it already exists in the dictionary provides a mechanism to update it

    Declaration
    public static Task<T> AddOrUpdate<K, T>(this IDictionary<K, T> items, K key, Func<Task<T>> getNewValue, Func<K, T, T> onUpdate)
    Parameters
    Type Name Description
    IDictionary<K, T> items

    The dictionary of items

    K key

    The key to add to the dictionary

    Func<Task<T>> getNewValue

    A function that runs a task to get the new value if the key does not already exist in the dictionary

    Func<K, T, T> onUpdate

    If the key exists a this function is called to update the existing value for that key.

    Returns
    Type Description
    Task<T>

    The item that was added, or updated, to the dictionary

    Type Parameters
    Name Description
    K

    The type of the key of the dictionary

    T

    The type of the value of the dictionary

    AddOrUpdate<K, T>(IDictionary<K, T>, K, T, Func<K, T, T>)

    Adds the specified item to the dictionary, or if it already exists in the dictionary provides a mechanism to update it

    Declaration
    public static T AddOrUpdate<K, T>(this IDictionary<K, T> items, K key, T newValue, Func<K, T, T> onUpdate)
    Parameters
    Type Name Description
    IDictionary<K, T> items

    The dictionary of items

    K key

    The key to add to the dictionary

    T newValue

    The new value to add to the dictionary if the key does not already exist

    Func<K, T, T> onUpdate

    If the key exists a this function is called to update the existing value for that key.

    Returns
    Type Description
    T

    The item that was added, or updated, to the dictionary

    Type Parameters
    Name Description
    K

    The type of the key of the dictionary

    T

    The type of the value of the dictionary

    AnyItems(IEnumerable)

    Returns true if the non generic list of items has any items contained in it

    Declaration
    public static bool AnyItems(this IEnumerable items)
    Parameters
    Type Name Description
    IEnumerable items

    A list of items to check to see if it containts 1 or more items

    Returns
    Type Description
    bool

    True if the list of items contains 1 or more items

    AreFormulaValuesEqual(object, object)

    Returns true if the specified values are equal to each other. Allows for a tolerance for equal due to formulas accuracy. So dates need only match to the minute and decimals to the 7th decimal place.

    Declaration
    public static bool AreFormulaValuesEqual(object x, object y)
    Parameters
    Type Name Description
    object x

    The first item to compare

    object y

    The second item to compare

    Returns
    Type Description
    bool

    True if the specified values are equal to each other. Allows for a tolerance for equal due to formulas accuracy. So dates need only match to the minute and decimals to the 7th decimal place.

    CapTo(decimal[], decimal[])

    Given an array of decimals, this makes sure the don't exceed an array of decimals holding a cap.

    If a decimal does the system lowers that decimal to the cap and adds it elsewhere in the array where there is excess room to the cap

    Declaration
    public static decimal[] CapTo(this decimal[] toCap, decimal[] cap)
    Parameters
    Type Name Description
    decimal[] toCap

    The set of decimals that should be modified to make sure they all fall within the specified caps

    decimal[] cap

    The set of decimals providing a cap for each associated original decimal

    Returns
    Type Description
    decimal[]

    A new set of decimals where each one conforms to the cap where possible

    Remarks

    For example

    var items = new decimal[] { 1, 2, 3, 4, 5 };
    var caps = new decimal[] { 1, 1, 3, 5, 5 };
    var results = items.CapTo(caps);

    Would result in

    1, 1, 3, 5, 5

    ClearToDateTimteWithNoOffset(DateTimeOffset)

    Clears the time and offset component of a date time

    Declaration
    public static DateTimeOffset ClearToDateTimteWithNoOffset(this DateTimeOffset dt)
    Parameters
    Type Name Description
    DateTimeOffset dt

    The datetime offset to have its time and offset values cleared

    Returns
    Type Description
    DateTimeOffset

    A new datetimeoffset without any time or offset values

    CombineHashCode(int, int)

    Combines two hashcodes in an efficient form

    Declaration
    public static int CombineHashCode(this int hashCode1, int hashCode2)
    Parameters
    Type Name Description
    int hashCode1

    The first hashcode to combine

    int hashCode2

    The second hashcode to combine

    Returns
    Type Description
    int

    A unique hashcode formed from the two hashcodes

    Remarks

    See stackoverflow.com/questions/18065251/concise-way-to-combine-field-hashcodes

    CountItems(IEnumerable)

    Counts all the items in the non generic collection

    Declaration
    public static int CountItems(this IEnumerable items)
    Parameters
    Type Name Description
    IEnumerable items

    The collection of items to count

    Returns
    Type Description
    int

    The number of items in the collection

    DelayWhileFalse(Func<bool>, int, int)

    Runs a func until it returns true, at the given delay, for the provided amount of times.

    Declaration
    public static Task<bool> DelayWhileFalse(this Func<bool> task, int delayMilliseconds, int maxRepeats)
    Parameters
    Type Name Description
    Func<bool> task
    int delayMilliseconds

    The delay, in ms

    int maxRepeats

    The number of times to run it

    Returns
    Type Description
    Task<bool>

    EqualToTheSecond(DateTimeOffset, DateTimeOffset)

    returns true if the specified date times are equal to each other to wthin a second

    Declaration
    public static bool EqualToTheSecond(this DateTimeOffset x, DateTimeOffset other)
    Parameters
    Type Name Description
    DateTimeOffset x

    The first date time to compare

    DateTimeOffset other

    The second date time to compare

    Returns
    Type Description
    bool

    True if both date times are equal to each other to within a second

    GetDuplicatesFromKeys<T, TKey>(IEnumerable<T>, Func<T, TKey>)

    Declaration
    public static List<T> GetDuplicatesFromKeys<T, TKey>(this IEnumerable<T> items, Func<T, TKey> keySelector) where TKey : IComparable<TKey>
    Parameters
    Type Name Description
    IEnumerable<T> items
    Func<T, TKey> keySelector
    Returns
    Type Description
    List<T>
    Type Parameters
    Name Description
    T
    TKey

    GetElapsedAndRestart(Stopwatch)

    Restarts the stopwatch, after grabbing the Elapsed.

    Declaration
    public static TimeSpan GetElapsedAndRestart(this Stopwatch stopwatch)
    Parameters
    Type Name Description
    Stopwatch stopwatch
    Returns
    Type Description
    TimeSpan

    GetIndex(IEnumerable, object)

    Returns the index a specified item exists within a non generic list of items

    Declaration
    public static int GetIndex(this IEnumerable items, object itemToFind)
    Parameters
    Type Name Description
    IEnumerable items

    The list of items to return the index of a mtachin item from

    object itemToFind

    The matching item to find the index it belonds in the specified list

    Returns
    Type Description
    int

    The index the itemToFind exists within the items collection. Returns -1 if it is not found.

    GetIndex<T>(IEnumerable<T>, Func<T, bool>)

    Retutns the index that the specified match function first matches an item in the list

    Declaration
    public static int GetIndex<T>(this IEnumerable<T> items, Func<T, bool> match)
    Parameters
    Type Name Description
    IEnumerable<T> items

    A set of items to enumerate through to find the first index of a specified matching item

    Func<T, bool> match

    A function that returns true when the specified item is found

    Returns
    Type Description
    int

    The index a specified matching item exists within a collection at. Returns -1 if not found.

    Type Parameters
    Name Description
    T

    The type of item to match against

    GetResult<T>(Task, Type)

    Awaits the specified task (that is an unknown Task of T), and returns the result cast to type T

    Declaration
    public static Task<T> GetResult<T>(this Task task, Type typeOfTaskResult)
    Parameters
    Type Name Description
    Task task
    Type typeOfTaskResult

    The actual type of the result for the task

    Returns
    Type Description
    Task<T>

    The result cast to type T

    Type Parameters
    Name Description
    T

    The type to cast the result to, not necessarily the actual type of the result

    GetService<T>(ValidationContext)

    Extension for ValidationContext. Calls GetService(Type) with a generic type.

    Declaration
    public static T GetService<T>(this ValidationContext context)
    Parameters
    Type Name Description
    ValidationContext context

    The validation context.

    Returns
    Type Description
    T
    Type Parameters
    Name Description
    T

    The type to get.

    GreaterThanOrEqualTo(IPAddress, IPAddress)

    Returns true if the specified IPAddress is greater than or equal to the other IP Address

    Declaration
    public static bool GreaterThanOrEqualTo(this IPAddress x, IPAddress y)
    Parameters
    Type Name Description
    IPAddress x

    The IP Address to see if it is greater than or equal to y

    IPAddress y

    The IP Address to see if it is less than or equal to x

    Returns
    Type Description
    bool

    True if the specified IPAddress is greater than or equal to the other IP Address

    HasNonDefaultValue<T>(T?)

    Indicates if the specified nullable value has a value that is not the default value of that type

    Declaration
    public static bool HasNonDefaultValue<T>(this T? item) where T : struct
    Parameters
    Type Name Description
    T? item

    The item to check to see if it holds a non default value for

    Returns
    Type Description
    bool

    True if the nullable item holds a value that isn't the default value of the type T

    Type Parameters
    Name Description
    T

    The type of the Nullable<T>

    HasValueEqualTo<T>(T?, T)

    Indicates if the specified nullable value has a value that is equal to the specified value

    Declaration
    public static bool HasValueEqualTo<T>(this T? item, T value) where T : struct
    Parameters
    Type Name Description
    T? item

    The item to check to see if it holds a value of

    T value

    The value to see if the item holds the same value of

    Returns
    Type Description
    bool

    True if the nullable item holds the specified value

    Type Parameters
    Name Description
    T

    The type of the Nullable<T>

    IsInRange(IPAddress, IPAddress, IPAddress)

    Returns true if the specified IPAddress is within the range of the start and end IPAddresses

    Declaration
    public static bool IsInRange(this IPAddress searchValue, IPAddress start, IPAddress end)
    Parameters
    Type Name Description
    IPAddress searchValue

    The IPAddress to determine if it exists between 2 other IP Addresses

    IPAddress start

    The start IP Address the searchValue can be equal to or greater than

    IPAddress end

    The end IP Address the searchValue can be equal to or less than

    Returns
    Type Description
    bool

    True if the specified searchValue IP Address is between (inclusive of) the start and end IP Addresses

    IsLastDayOfMonth(DateTime)

    Returns true if the specified date is the last day of a month

    Declaration
    public static bool IsLastDayOfMonth(this DateTime dt)
    Parameters
    Type Name Description
    DateTime dt

    The date to evaluate if it occurs on the last day of a month or not

    Returns
    Type Description
    bool

    True if the specified date is the last day of a month

    IsNullOrDefault<T>(T?)

    Declaration
    public static bool IsNullOrDefault<T>(this T? item) where T : struct
    Parameters
    Type Name Description
    T? item
    Returns
    Type Description
    bool
    Type Parameters
    Name Description
    T

    ItemsAreEqual(IEnumerable, IEnumerable)

    Returns true if both lists contain the same items in the same order

    Declaration
    public static bool ItemsAreEqual(this IEnumerable items, IEnumerable otherItems)
    Parameters
    Type Name Description
    IEnumerable items

    First list of items to compare

    IEnumerable otherItems

    Second list of items to compare

    Returns
    Type Description
    bool

    True if the item collections are the same size and contain the same items in each position

    LessThanOrEqualTo(IPAddress, IPAddress)

    Returns true if the specified IPAddress is less than or equal to the other IP Address

    Declaration
    public static bool LessThanOrEqualTo(this IPAddress x, IPAddress y)
    Parameters
    Type Name Description
    IPAddress x

    The IP Address to see if it is less than or equal to y

    IPAddress y

    The IP Address to see if it is greater than or equal to x

    Returns
    Type Description
    bool

    True if the specified IPAddress is less than or equal to the other IP Address

    Matches<T>(T?, T?)

    Declaration
    public static bool Matches<T>(this T? item, T? value) where T : struct
    Parameters
    Type Name Description
    T? item
    T? value
    Returns
    Type Description
    bool
    Type Parameters
    Name Description
    T

    SetIfNotEqual<T, TP>(T, Expression<Func<T, TP>>, TP)

    Allows you to set the value of a specific property only if it is not equal to the value you want to set it to. Returns false if it didn't set the property as it already holds the specified value

    Declaration
    public static bool SetIfNotEqual<T, TP>(this T value, Expression<Func<T, TP>> propName, TP propValue)
    Parameters
    Type Name Description
    T value

    The item you want to set the property against it to a certain value

    Expression<Func<T, TP>> propName

    An expression that gives the property you want to set

    TP propValue

    The value to call and set the property with only if it is currently not equal to that value

    Returns
    Type Description
    bool

    True if the value was set or false otherwise (indicating it already has that value)

    Type Parameters
    Name Description
    T

    The type of the item you are setting a property against

    TP

    The type of the property value to be set

    Remarks

    For example:

    public class MyItem
    {
        public int Val { get; set; }
    }
    
    public static void SetValue()
    {
        var myItem = new MyItem() { Val = 1 };
        myItem.SetIfNotEqual(x => x.Val, 1);
        myItem.SetIfNotEqual(x => x.Val, 2);
    }

    Will result in the myItem Val property not being set to the value 1 on the first call, then subsequently it will be set to the value 2 on the second.

    This ensures you don't set property values when you don't want trigger notification changes or anything else

    ToAsyncEnumerable<T>(IEnumerable<T>)

    Returns an IAsyncEnumerable for a given IEnumerable in order to maintain consistent use with enumerations that implement both.

    Declaration
    public static IAsyncEnumerable<T> ToAsyncEnumerable<T>(this IEnumerable<T> enumerable)
    Parameters
    Type Name Description
    IEnumerable<T> enumerable

    An enumerable collection of type T

    Returns
    Type Description
    IAsyncEnumerable<T>

    Returns an IAsyncEnumerable that enumerates the provided IEnumerable.

    Type Parameters
    Name Description
    T

    The type of the items in the collection to enumerate

    ToByteArray(Stream)

    Returns the entire contents of the specified stream as a byte array

    Declaration
    public static byte[]? ToByteArray(this Stream s)
    Parameters
    Type Name Description
    Stream s

    The stream to return the contents of

    Returns
    Type Description
    byte[]

    The entire contents of the specified stream as a byte array

    ToCollectionDictionary<TKey, T>(IEnumerable<T>, Func<T, TKey>)

    Converts a list of items into a dictionary of lists each grouped by a specified key

    Declaration
    public static Dictionary<TKey, List<T>> ToCollectionDictionary<TKey, T>(this IEnumerable<T> items, Func<T, TKey> keySelector)
    Parameters
    Type Name Description
    IEnumerable<T> items

    The list of items to convert into a dictionary

    Func<T, TKey> keySelector

    A function that given an item of type T returns the dictionary key it would belong to

    Returns
    Type Description
    Dictionary<TKey, List<T>>

    A new dictionary holding a list of items for each dictionary key

    Type Parameters
    Name Description
    TKey

    The type of the property that holds the key for the dictionary

    T

    The type of items being converted into a dictionary

    ToCollectionDictionary<TKey, T, TVAL>(IEnumerable<T>, Func<T, TKey>, Func<T, TVAL>)

    Converts a list of items into a dictionary of lists each grouped by a specified key

    Declaration
    public static Dictionary<TKey, List<TVAL>> ToCollectionDictionary<TKey, T, TVAL>(this IEnumerable<T> items, Func<T, TKey> keySelector, Func<T, TVAL> valueSelector)
    Parameters
    Type Name Description
    IEnumerable<T> items

    The list of items to convert into a dictionary

    Func<T, TKey> keySelector

    A function that given an item of type T returns the dictionary key it would belong to

    Func<T, TVAL> valueSelector

    A function that given an item of type T returns the value to use

    Returns
    Type Description
    Dictionary<TKey, List<TVAL>>

    A new dictionary holding a list of items for each dictionary key

    Type Parameters
    Name Description
    TKey

    The type of the property that holds the key for the dictionary

    T

    The type of items being converted into a dictionary

    TVAL

    ToConcurrentCollectionDictionary<TKey, T>(IEnumerable<T>, Func<T, TKey>)

    Converts a list of items into a concurrent dictionary of lists each grouped by a specified key

    Declaration
    public static ConcurrentDictionary<TKey, List<T>> ToConcurrentCollectionDictionary<TKey, T>(this IEnumerable<T> items, Func<T, TKey> keySelector)
    Parameters
    Type Name Description
    IEnumerable<T> items

    The list of items to convert into a dictionary

    Func<T, TKey> keySelector

    A function that given an item of type T returns the dictionary key it would belong to

    Returns
    Type Description
    ConcurrentDictionary<TKey, List<T>>

    A new dictionary holding a list of items for each dictionary key

    Type Parameters
    Name Description
    TKey

    The type of the property that holds the key for the dictionary

    T

    The type of items being converted into a dictionary

    ToDictionaryOfDictionary<TKey1, TKey2, T>(IEnumerable<T>, Func<T, TKey1>, Func<T, TKey2>)

    Returns a dictionary of dictionaries from a given list of items

    Declaration
    public static Dictionary<TKey1, Dictionary<TKey2, T>> ToDictionaryOfDictionary<TKey1, TKey2, T>(this IEnumerable<T> items, Func<T, TKey1> key1Selector, Func<T, TKey2> key2Selector)
    Parameters
    Type Name Description
    IEnumerable<T> items

    The collection of items to organize into dictionaries

    Func<T, TKey1> key1Selector

    A function that given an item will return the key to group it by in the first dictionary

    Func<T, TKey2> key2Selector

    A function that given an item will return the key to group it by in the second dictionary

    Returns
    Type Description
    Dictionary<TKey1, Dictionary<TKey2, T>>

    A dictionary of dictionaries that has all the items organized within it

    Type Parameters
    Name Description
    TKey1

    The type of the key for the first dictionary

    TKey2

    The type of the key for the second dictionary

    T

    The type of items being organized into dictionaries

    ToFullExceptionMessage(Exception?, bool)

    Returns The message of an exception and all inner exception messages as well.

    Optionally includes the stack

    Declaration
    public static string ToFullExceptionMessage(this Exception? ex, bool withStackTrace = false)
    Parameters
    Type Name Description
    Exception ex

    The exception to return the message from

    bool withStackTrace

    Indicates if the stack trace should be included with the message too

    Returns
    Type Description
    string

    The message of the provided exception, and all recursive inner exceptions, along with the stack trace if included

    ToFullStackTrace(Exception)

    Returns the stack trace component of an exception and all inner exceptions

    Declaration
    public static string ToFullStackTrace(this Exception ex)
    Parameters
    Type Name Description
    Exception ex

    The exception to display the stack trace of

    Returns
    Type Description
    string

    The stack trace of an exception and all inner exceptions

    ToNewDateOrderedGuid(Guid)

    Creates a new GUID with the last 8 bytes of the guid containing a date component ensuring that guids are created in an order sorted by SQL Server

    Declaration
    public static Guid ToNewDateOrderedGuid(this Guid value)
    Parameters
    Type Name Description
    Guid value

    Not required. Guid.Empty is fine.

    Returns
    Type Description
    Guid

    A new GUID with the last 8 bytes of the guid containing a date component ensuring that guids are created in an order sorted by SQL Server

    Remarks

    See https://netmatze.wordpress.com/2012/03/08/generate-sequencial-guid/

    This is used to ensure GUIDs that are used in SQL Server as part of clustered indexes are always added at the end so data doesn't have to be moved

    ToShortInternationalDate(DateTime)

    Returns the specified value formatted in date international format

    Declaration
    public static string ToShortInternationalDate(this DateTime value)
    Parameters
    Type Name Description
    DateTime value

    The date time to be formatted

    Returns
    Type Description
    string

    A formatted string of the date time in date international format

    See Also
    DateInternationalFormat

    ToShortInternationalDate(DateTimeOffset)

    Returns the specified value formatted in date international format

    Declaration
    public static string ToShortInternationalDate(this DateTimeOffset value)
    Parameters
    Type Name Description
    DateTimeOffset value

    The date time offset to be formatted

    Returns
    Type Description
    string

    A formatted string of the date time offset in date time friendly format for file names

    See Also
    DateInternationalPreciseFormat

    ToShortInternationalDateTime(DateTime)

    Returns the specified value formatted in date international precise format

    Declaration
    public static string ToShortInternationalDateTime(this DateTime value)
    Parameters
    Type Name Description
    DateTime value

    The date time to be formatted

    Returns
    Type Description
    string

    A formatted string of the date time in date international precise format

    See Also
    DateInternationalPreciseFormat

    ToShortInternationalDateTime(DateTimeOffset)

    Returns the specified value formatted in date international precise format

    Declaration
    public static string ToShortInternationalDateTime(this DateTimeOffset value)
    Parameters
    Type Name Description
    DateTimeOffset value

    The date time offset to be formatted

    Returns
    Type Description
    string

    A formatted string of the date time offset in date international precise format

    See Also
    DateInternationalPreciseFormat

    ToShortInternationalDateTimeFileNameFriendly(DateTime)

    Returns the specified value formatted in date time friendly format for file names

    Declaration
    public static string ToShortInternationalDateTimeFileNameFriendly(this DateTime value)
    Parameters
    Type Name Description
    DateTime value

    The date time to be formatted

    Returns
    Type Description
    string

    A formatted string of the date time in date time friendly format for file names

    See Also
    DateTimeFileFriendlyFormat

    ToShortInternationalDateTimeFileNameFriendly(DateTimeOffset)

    Returns the specified value formatted in date time friendly format for file names

    Declaration
    public static string ToShortInternationalDateTimeFileNameFriendly(this DateTimeOffset value)
    Parameters
    Type Name Description
    DateTimeOffset value

    The date time offset to be formatted

    Returns
    Type Description
    string

    A formatted string of the date time offset in date time friendly format for file names

    See Also
    DateTimeFileFriendlyFormat

    ToShortInternationalDateTimeNoSeconds(DateTime)

    Returns the specified value formatted in date international with time and no seconds

    Declaration
    public static string ToShortInternationalDateTimeNoSeconds(this DateTime value)
    Parameters
    Type Name Description
    DateTime value

    The date time to be formatted

    Returns
    Type Description
    string

    A formatted string of the date time in date international with time and no seconds

    See Also
    DateInternationalTimeNoSecondsFormat

    ToSizedCollections<T>(IEnumerable<T>, int)

    Given a collection, this splits it up into x collections of max size collectionMaxSize

    Declaration
    public static IEnumerable<List<T>> ToSizedCollections<T>(this IEnumerable<T> items, int collectionMaxSize)
    Parameters
    Type Name Description
    IEnumerable<T> items

    The collection to split up into multiple collections each of max size collectionMaxSize

    int collectionMaxSize

    The max number of items that can be contained in any one collection the method returns

    Returns
    Type Description
    IEnumerable<List<T>>

    A collection of collections each of max size collectionMaxSize

    Type Parameters
    Name Description
    T

    The type of items in the collection

    ToUserFriendlyTimePeriodWithSeconds(TimeSpan)

    Returns a user friendly description of a time spane

    Declaration
    public static string ToUserFriendlyTimePeriodWithSeconds(this TimeSpan period)
    Parameters
    Type Name Description
    TimeSpan period

    The time span to provide a user friendly description for

    Returns
    Type Description
    string

    A suer friendly description of a given time span

    Remarks

    For instance the following types of formats can be returned:

    1 second

    x hours y minutes z seconds

    y minutes z seconds

    z seconds

    WithNoOffset(DateTimeOffset, bool)

    Declaration
    public static DateTimeOffset WithNoOffset(this DateTimeOffset dt, bool dateComponentOnly)
    Parameters
    Type Name Description
    DateTimeOffset dt
    bool dateComponentOnly
    Returns
    Type Description
    DateTimeOffset
    In this article
    Back to top © LemonEdge Technologies. All rights reserved.