Search Results for

    Show / Hide Table of Contents

    Class MiscExtensions

    A set of miscellaneous extension and helper methods

    Inheritance
    System.Object
    MiscExtensions
    Inherited Members
    System.Object.Equals(System.Object)
    System.Object.Equals(System.Object, System.Object)
    System.Object.GetHashCode()
    System.Object.GetType()
    System.Object.MemberwiseClone()
    System.Object.ReferenceEquals(System.Object, System.Object)
    System.Object.ToString()
    Namespace: LemonEdge.Utils
    Assembly: 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
    System.Collections.Generic.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, 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
    System.Collections.Generic.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

    System.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

    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
    System.Collections.Generic.IDictionary<K, T> items

    The dictionary of items

    K key

    The key to add to the dictionary

    System.Func<System.Threading.Tasks.Task<T>> getNewValue

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

    System.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
    System.Threading.Tasks.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

    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
    System.Collections.IEnumerable items

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

    Returns
    Type Description
    System.Boolean

    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
    System.Object x

    The first item to compare

    System.Object y

    The second item to compare

    Returns
    Type Description
    System.Boolean

    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
    System.Decimal[] toCap

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

    System.Decimal[] cap

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

    Returns
    Type Description
    System.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
    System.DateTimeOffset dt

    The datetime offset to have its time and offset values cleared

    Returns
    Type Description
    System.DateTimeOffset

    A new datetimeoffset without any time or offset values

    CombineHashCode(Int32, Int32)

    Combines two hashcodes in an efficient form

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

    The first hashcode to combine

    System.Int32 hashCode2

    The second hashcode to combine

    Returns
    Type Description
    System.Int32

    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
    System.Collections.IEnumerable items

    The collection of items to count

    Returns
    Type Description
    System.Int32

    The number of items in the collection

    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
    System.DateTimeOffset x

    The first date time to compare

    System.DateTimeOffset other

    The second date time to compare

    Returns
    Type Description
    System.Boolean

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

    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
    System.Collections.IEnumerable items

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

    System.Object itemToFind

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

    Returns
    Type Description
    System.Int32

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

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

    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
    System.Collections.Generic.IEnumerable<T> items

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

    System.Func<T, System.Boolean> match

    A function that returns true when the specified item is found

    Returns
    Type Description
    System.Int32

    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
    System.Threading.Tasks.Task task
    System.Type typeOfTaskResult

    The actual type of the result for the task

    Returns
    Type Description
    System.Threading.Tasks.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

    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
    System.Net.IPAddress x

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

    System.Net.IPAddress y

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

    Returns
    Type Description
    System.Boolean

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

    HasNonDefaultValue<T>(Nullable<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
    System.Nullable<T> item

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

    Returns
    Type Description
    System.Boolean

    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 System.Nullable<T>

    HasValueEqualTo<T>(Nullable<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
    System.Nullable<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
    System.Boolean

    True if the nullable item holds the specified value

    Type Parameters
    Name Description
    T

    The type of the System.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
    System.Net.IPAddress searchValue

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

    System.Net.IPAddress start

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

    System.Net.IPAddress end

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

    Returns
    Type Description
    System.Boolean

    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
    System.DateTime dt

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

    Returns
    Type Description
    System.Boolean

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

    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
    System.Collections.IEnumerable items

    First list of items to compare

    System.Collections.IEnumerable otherItems

    Second list of items to compare

    Returns
    Type Description
    System.Boolean

    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
    System.Net.IPAddress x

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

    System.Net.IPAddress y

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

    Returns
    Type Description
    System.Boolean

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

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

    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, P>(this T value, Expression<Func<T, P>> propName, P propValue)
    Parameters
    Type Name Description
    T value

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

    System.Linq.Expressions.Expression<System.Func<T, P>> propName

    An expression that gives the property you want to set

    P propValue

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

    Returns
    Type Description
    System.Boolean

    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

    P

    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

    Test()

    Declaration
    public static void Test()

    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
    System.IO.Stream s

    The stream to return the contents of

    Returns
    Type Description
    System.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
    System.Collections.Generic.IEnumerable<T> items

    The list of items to convert into a dictionary

    System.Func<T, TKey> keySelector

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

    Returns
    Type Description
    System.Collections.Generic.Dictionary<TKey, System.Collections.Generic.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
    System.Collections.Generic.IEnumerable<T> items

    The collection of items to organize into dictionaries

    System.Func<T, TKey1> key1Selector

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

    System.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
    System.Collections.Generic.Dictionary<TKey1, System.Collections.Generic.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, Boolean)

    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
    System.Exception ex

    The exception to return the message from

    System.Boolean withStackTrace

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

    Returns
    Type Description
    System.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
    System.Exception ex

    The exception to display the stack trace of

    Returns
    Type Description
    System.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
    System.Guid value

    Not required. Guid.Empty is fine.

    Returns
    Type Description
    System.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
    System.DateTime value

    The date time to be formatted

    Returns
    Type Description
    System.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
    System.DateTimeOffset value

    The date time offset to be formatted

    Returns
    Type Description
    System.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
    System.DateTime value

    The date time to be formatted

    Returns
    Type Description
    System.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
    System.DateTimeOffset value

    The date time offset to be formatted

    Returns
    Type Description
    System.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
    System.DateTime value

    The date time to be formatted

    Returns
    Type Description
    System.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
    System.DateTimeOffset value

    The date time offset to be formatted

    Returns
    Type Description
    System.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
    System.DateTime value

    The date time to be formatted

    Returns
    Type Description
    System.String

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

    See Also
    DateInternationalTimeNoSecondsFormat

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

    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
    System.Collections.Generic.IEnumerable<T> items

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

    System.Int32 collectionMaxSize

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

    Returns
    Type Description
    System.Collections.Generic.IEnumerable<System.Collections.Generic.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
    System.TimeSpan period

    The time span to provide a user friendly description for

    Returns
    Type Description
    System.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

    In This Article
    Back to top © LemonTree Software Ltd. All rights reserved.