• Avalanche.Core
Search Results for

    Show / Hide Table of Contents
    • Avalanche.Accessor
      • Introduction
      • IAccessor
        • IAccessor
        • IListAccessor
        • IMapAccessor
        • IRecordAccessor
        • IContentAccessor
        • IOneOfAccessor
        • IAnyAccessor
      • .Net
        • Introduction
        • IList<T>
        • IDictionary<K,V>
        • FieldInfo
        • OneOfAttribute
        • StructLayoutAttribute
        • Class
      • Protobuf
        • Introduction
      • Articles
        • Dependency Injection
        • AccessorMessages
    • Avalanche.Binding
      • Introduction
    • Avalanche.Configuration
      • Introduction
      • Configuration Binding
      • ConfigurationExtensions
      • MemoryConfiguration
      • PrintTree
      • Saving IOptions
      • Yaml
    • Avalanche.Converter
      • Introduction
      • EnumConverter
      • Func<,>
      • HexConverter
      • PrimitiveConverter
      • StringConverter
    • Avalanche.Core
      • License
    • Avalanche.DataType
      • Introduction
      • DataType
        • IDataType
        • IListType
        • IMapType
        • IRecordType
        • IFieldType
        • IOneOfType
        • IAnyType
        • IStringType
        • IValueType
        • IIntegerType
        • IEnumerationType
        • IRealType
      • .Net
        • Introduction
        • IList<T>
        • IDictionary<K,V>
        • FieldInfo
        • Enum
        • OneOfAttribute
        • StructLayoutAttribute
        • Class
      • Protobuf
        • Introduction
      • Articles
        • DataTypeRequest
        • PrintTree
        • DataTypeMessages
    • Avalanche.Emit
      • Introduction
      • TypeBuilder
      • ConstructorBuilder
      • MethodBuilder
      • PropertyBuilder
      • FieldBuilder
      • Emit
      • Utilities
    • Avalanche.FileSystem
      • Introduction
      • Abstractions
        • IFileSystem
          • IFileSystemBrowse
          • IFileSystemCreateDirectory
          • IFileSystemDelete
          • IFileSystemFileAttribute
          • IFileSystemMount
          • IFileSystemMove
          • IFileSystemObserve
          • IFileSystemOpen
        • IEvent
        • IEntry
        • IOption
        • IToken
      • FileSystem
      • VirtualFileSystem
      • MemoryFileSystem
      • EmbeddedFileSystem
      • HttpFileSystem
      • Decoration
      • IFileProvider
      • Events
      • Utilities
        • Dispose
        • File Scanner
        • Visit Tree
        • File Operation
        • FilterEnumerable
        • PollingFilterWatchToken
    • Avalanche.Identity
      • Introduction
      • Identity
      • IdentityParts
      • IdentityInterner
      • IdentityComparer
      • Print Tree
      • IdentityAccessors
        • Introduction
        • TypeName
    • Avalanche.Localization
      • Introduction
      • Localization
      • LocalizationFile
      • LocalizationFiles
      • LocalizationFileSystem
      • LocalizationFileFormat
      • LocalizationLine
      • LocalizationLines
      • TemplateFormat
      • CultureProvider
      • FallbackCultureProvider
      • ResourceManager
      • LocalizationError
      • Microsoft.Extensions
        • Introduction
        • DependencyInjection
        • FileProvider
        • Logging
        • ITextLocalizer
        • IFileLocalizer
        • Localization
      • Asp.Net
        • Introduction
        • Supplying localization
        • Inject to pages
        • Culture Assigned
        • Minimalistic Api
        • Diagnostics
      • Pluralization
        • Introduction
        • Multiple plural parameters
        • Custom PluralRules
        • Invariant Culture
        • Unit Prefix
        • IPluralRule
        • IPluralNumber
        • IPluralRules
        • CLDRs
        • Unicode.CLDR40
        • Unicode.CLDR41
        • Unicode.CLDR42
      • Articles
        • Alphabet localization
        • Benchmarks
        • Caching
        • Class Library
        • Demo
        • Diagnostics
        • Embedded resources
        • Emplacement
        • File localization
        • Text localization
        • Printing templates
    • Avalanche.Message
      • Introduction
      • IMessage
      • IMessageProvider
      • IMessageDescription
      • IMessageDescriptions
      • MessageLevel
      • Message printing
      • Messages and Exceptions
      • Microsoft.Extensions
        • DependencyInjection
      • Articles
        • Aggregate Messages
        • Localization
        • Logging
        • Validation
    • Avalanche.Options
      • Introduction
      • OptionsExtensions
      • OptionsMonitorCast
    • Avalanche.Service
      • Introduction
      • Service
        • Introduction
        • IService
        • IServiceDisposable
        • IServiceDecoration
        • IServiceCast
        • IServiceObservable
        • IServiceContainer
        • Construction
        • Query
        • CancellationToken
        • CachePolicy
        • Scope
      • Handler
        • Introduction
        • IHandler
        • IHandlerCast
        • IHandlerDecoration
        • IHandlerWithOrder
        • CancellationToken
        • Cyclicity
        • Delegates
        • Invokable
        • ExportAttribute
        • OrderAttribute
        • PrintTree
        • Recursion
      • Query
        • Introduction
        • IQuery
        • IQueryCast
        • IQueryDecoration
      • Entry
        • Introduction
        • IEntry
        • IEntryCast
        • IEntryDecoration
        • IEntryObservable
        • IEntryVisitable
        • EntryState
      • Request
        • Introduction
        • IRequest
        • IRequestFor
        • IRequestToBeCached
        • IRequestToBeDisposed
        • RequestAttribute
        • ContextParameterAttribute
        • Print Tree
      • Dependency Injection
        • Introduction
        • Asp.Net
        • ServiceRequest<T>
        • Decorating a service
        • Handler
        • CachePolicy
        • CancellationToken
        • QueryLogger
        • IHostBuilder
      • Examples
        • NodeCount
        • Expression
        • Mapper
      • Articles
        • Benchmarks
        • Error Handling
        • ServiceMessages
    • Avalanche.StatusCode
      • Introduction
      • HResult
        • Introduction
        • HResult.Facilities
        • BasicMessages
        • RpcMessages
        • DispatchMessages
        • StorageMessages
        • ItfMessages
        • Win32Messages
        • WindowsMessages
        • SspiMessages
        • CertMessages
        • MediaServerMessages
        • SetupApiMessages
        • ScardMessages
        • ComPlusMessages
        • ClrMessages
        • UserModeFilterManagerMessages
        • GraphicsMessages
        • TpmServicesMessages
        • TpmSoftwareMessages
        • PlaMessages
        • FveMessages
        • FwpMessages
        • NdisMessages
        • DltMessages
      • System
        • Introduction
        • AccessControlMessages
        • AggregateMessages
        • AppDomainMessages
        • ArgumentMessages
        • ArgumentNullMessages
        • ArgumentOutOfRangeMessages
        • ArithmeticMessages
        • ArrayMessages
        • AssemblyMessages
        • BadImageFormatMessages
        • CodeContractMessages
        • CodePageMessages
        • CollectionsMessages
        • CompilerServiceMessages
        • CryptographyMessages
        • CultureMessages
        • DiagnosticsMessages
        • EventSourceMessages
        • ExecutionEngineMessages
        • FormatMessages
        • HostProtectionMessages
        • IOMessages
        • IndexOutOfRangeMessages
        • InteropServiceMessages
        • InvalidCastMessages
        • InvalidOperationMessages
        • IsolatedStorageMessages
        • LazyMessages
        • MarshalerMessages
        • MemoryMessages
        • MiscellaneousMessages
        • NotImplementedMessages
        • NotSupportedMessages
        • ObjectDisposedMessages
        • OperationCanceledMessages
        • OverflowMessages
        • PlatformMessages
        • PolicyMessages
        • PrincipalMessages
        • ProgramMessages
        • ReferenceMessages
        • ReflectionMessages
        • RegionMessages
        • RemotingMessages
        • ResourcesMessages
        • SecurityMessages
        • SerializationMessages
        • StackMessages
        • TaskMessages
        • TextMessages
        • ThreadingMessages
        • TimeZoneMessages
        • TypeMessages
        • XmlMessages
      • HttpStatusCode
      • OpcUaStatusCode
    • Avalanche.Template
      • Introduction
      • TemplateFormats
      • ITemplatePrintable
      • ITemplateFormatPrintable
      • ITemplateText
      • ITemplateBreakdown
      • ITemplateFormat
      • ITemplateFormats
      • Extract Arguments
      • Emplacement
    • Avalanche.Tokenizer
      • Introduction
      • IToken
      • ITokenizer
      • Tokenizers
    • Avalanche.Utilities
      • Introduction
      • Collections
        • Tuples
        • StructList
        • ArrayList
        • BijectionMap
        • LocakableDictionary
        • LockableList
        • MapList
        • Pipe
        • RingQueue
        • EnumerableExtensions
        • TupleUtilities
        • ArrayUtilities
      • Comparers
        • IGraphComparer
        • IGraphComparable
        • AlphaNumericComparer
        • EnumerableComparer
        • EnumerableGraphComparer
        • ReferenceComparer
        • KeyValuePairComparer
        • DefaultComparerProvider
        • RecordComparer
      • Cloners
        • ICloner
        • IGraphCloner
        • IGraphCloneable
        • ListCloner
        • DictionaryCloner
        • FieldCloner
        • PassthroughCloner
        • RecordCloner
        • ClonerProvider
      • Dispose
        • IDisposeAttachable
        • IDisposeBelatable
      • Provider
        • Introduction
        • ProviderBase
        • Delegate
        • Pipe
        • Cache
        • ResultCapture
        • AsReadOnly
        • AsService
        • IProviderEvent
      • Record
        • IRecordDescription
        • IFieldDescription
        • IConstructorDescription
        • IConstructionDescription
        • IParameterDescription
        • IRecordProviders
        • RecordDelegates
          • RecordCreate
          • RecordClone
          • RecordCopy
          • IRecordDelegates
        • FieldDelegates
          • FieldRead
          • FieldWrite
          • RecreateWith
          • IFieldDelegates
      • Reflection
        • EnumDescription
      • String
        • IEscaper
        • UnicodeString
        • Hex
      • Miscellaneous
        • IIdGenerator
        • Permutation
        • IReadOnly
        • IUserDataContainer
        • ITreeNode
        • Void
    • Avalanche.Writer
      • Introduction
      • ConstantWriter
      • Context
      • ConvertWriter
      • DefaultConstructor
      • DelegateWriter
      • PassthroughWriter
      • Referer
      • TypeCast
      • Writer
      • WriterPipe
      • WriterMessages

    ArrayUtilities

    ArrayUtilities.Add(ref array, element) adds an element to array. Writes a new array to ref pointer.

    int[]? array = { 1, 2, 3 };
    ArrayUtilities.Add(ref array, 4);
    

    ArrayUtilities.Append(array, element) returns a new array with element appended.

    int[] array = { 1, 2, 3 };
    array = ArrayUtilities.Append(array, 4);
    

    ArrayUtilities.AppendIfNotNull(array, element) appends an element to array if element is not null. Returns a new array if element was appended.

    string[] array = { "A", "B", "C" };
    array = ArrayUtilities.AppendIfNotNull(array, "D");
    array = ArrayUtilities.AppendIfNotNull(array, null);
    

    ArrayUtilities.Remove(ref array, element) removes an element. Uses comparer to identify element. If value was removed, writes a new array to ref pointer.

    string[]? array = { "A", "B", "C" };
    ArrayUtilities.Remove(ref array, "B");
    

    ArrayUtilities.Remove(ref array, element, comparer?) removes first element where comparer determines equality. If value was removed, writes a new array to ref pointer.

    object[]? array = { new object(), new object(), new object() };
    object objectToRemove = array[1];
    ArrayUtilities.Remove(ref array, objectToRemove, comparer: ReferenceEqualityComparer<object>.Instance);
    

    ArrayUtilities.Remove(ref array, element, assignNullIfEmptied) assigns null if assignNullIfEmptied is true and array gets emptied.

    string[]? array = { "A", "B", "C" };
    ArrayUtilities.Remove(ref array, "A");
    ArrayUtilities.Remove(ref array, "B");
    ArrayUtilities.Remove(ref array, "C", assignNullIfEmptied: true);
    

    ArrayUtilities.RemoveAt(ref array, index) removes an element at index. Writes a new array to ref pointer.

    string[]? array = { "A", "B", "C" };
    ArrayUtilities.RemoveAt(ref array, 1);
    

    ArrayUtilities.Without(array, element, comparer?) returns a new array without an element. Element is identified with comparer.

    string[] array = { "A", "B", "C" };
    array = ArrayUtilities.Without(array, "B");
    array = ArrayUtilities.Without(array, "c", comparer: StringComparer.InvariantCultureIgnoreCase);
    

    ArrayUtilities.WithoutAt(array, element) returns a new array without an element at specified index.

    string[] array = { "A", "B", "C" };
    array = ArrayUtilities.WithoutAt(array, 1);
    

    ArrayUtilities.Without(array, element, assignNullIfEmptied) returns null if assignNullIfEmptied is true and array gets emptied.

    string[] array = { "A", "B", "C" };
    array = ArrayUtilities.Without(array, "A");
    array = ArrayUtilities.Without(array, "B");
    array = ArrayUtilities.Without(array, "C", assignNullIfEmptied: true);
    

    ArrayUtilities.EmptyArray() returns empty array T[] singleton.

    string[] array = Array.Empty<string>();
    string[] array_ = (string[])ArrayUtilities.EmptyArray(typeof(string));
    

    array.Slice(index, length) returns a new array that contains a slice of an array.

    string[] array = { "A", "B", "C", "D", "E", "F" };
    string[] slice = array.Slice(3, 3); // "D", "E", "F"
    

    array.IndexOfSequence(sequence, comparer?) finds index of a sub sequence.

    string[] array = { "A", "B", "C", "D", "E", "F" };
    string[] subarray = { "D", "E", "F" };
    WriteLine(array.IndexOfSequence(subarray)); // 3
    

    array.StartsWith(sequence) tests whether array starts with sequence.

    string[] array = { "A", "B", "C", "D", "E", "F" };
    string[] subarray = { "A", "B", "C" };
    WriteLine(array.StartsWith(subarray)); // True
    

    ArrayUtilities.ArraySelect(matrix, selector) creates a new multi-rank array where selector has been applied on each element.

    int[,] matrix = new int[4, 4];
    matrix[0, 0] = 10;
    matrix = (int[,])ArrayUtilities.ArraySelect(matrix, (int x) => x * x);
    WriteLine(matrix[0, 0]); // 100
    

    ArrayUtilities.Flatten(matrix) flattens multi-rank array into enumerable of elements.

    int[,,] matrix = new int[3, 3, 3];
    IEnumerable<int> values = ArrayUtilities.Flatten<int>(matrix);
    

    ArrayUtilities.VisitArray<T>(array) visits each element with array indices.

    int[,] matrix = new int[4, 4];
    foreach ((int[] indices, int value) in ArrayUtilities.VisitArray<int>(matrix))
        WriteLine($"[{string.Join(", ", indices)}] = {value}"); // [0, 0] = 0
    

    ArrayUtilities.VisitArrays<T>(array1, array2) visits two arrays of same dimensions.

    int[,] matrix1 = new int[4, 4];
    int[,] matrix2 = new int[4, 4];
    foreach ((int[] indices, int value1, int value2) in ArrayUtilities.VisitArrays<int>(matrix1, matrix2))
        WriteLine($"[{string.Join(", ", indices)}] = {value1} and {value2}"); // [0, 0] = 0 and 0
    

    ArrayUtilities.GetInstancesOf<T, V>(array) returns instances of V.

    object[] array = { new object(), "Hello", "World", 5, true };
    string[] strings = array.GetInstancesOf<object, string>();
    int[] ints = array.GetInstancesOf<object, int>();
    bool[] bools = array.GetInstancesOf<object, bool>();
    object[] objs = array.GetInstancesOf<object, object>(); // object, "Hello", "World", 5, true
    

    ArrayUtilities.GetFirstInstanceOf<T, V>(array) returns first instance of V.

    object[] array = { new object(), "Hello", "World", 5, true };
    string firstString = array.GetFirstInstanceOf<object, string>();     // "Hello"
    int firstInt = array.GetFirstInstanceOf<object, int>();              // 5
    bool firstBool = array.GetFirstInstanceOf<object, bool>();           // true
    

    ArrayUtilities.TryGetFirstInstanceOf<T, V>(array) tries to return first instance of V.

    object[] array = { new object(), "Hello", "World", 5, true };
    if (array.TryGetFirstInstanceOf(out string firstString)) WriteLine(firstString); // "Hello"
    

    Full Example

    Full example
    using System;
    using System.Collections.Generic;
    using Avalanche.Utilities;
    using static System.Console;
    
    public class arrayutilities
    {
        public static void Run()
        {
            {
                // <01>
                int[]? array = { 1, 2, 3 };
                ArrayUtilities.Add(ref array, 4);
                // </01>
            }
            {
                // <02>
                int[] array = { 1, 2, 3 };
                array = ArrayUtilities.Append(array, 4);
                // </02>
            }
    
            {
                // <03>
                string[] array = { "A", "B", "C" };
                array = ArrayUtilities.AppendIfNotNull(array, "D");
                array = ArrayUtilities.AppendIfNotNull(array, null);
                // </03>
            }
            {
                // <04>
                string[]? array = { "A", "B", "C" };
                ArrayUtilities.Remove(ref array, "B");
                // </04>
            }
            {
                // <05>
                object[]? array = { new object(), new object(), new object() };
                object objectToRemove = array[1];
                ArrayUtilities.Remove(ref array, objectToRemove, comparer: ReferenceEqualityComparer<object>.Instance);
                // </05>
            }
    
            {
                // <06>
                string[]? array = { "A", "B", "C" };
                ArrayUtilities.Remove(ref array, "A");
                ArrayUtilities.Remove(ref array, "B");
                ArrayUtilities.Remove(ref array, "C", assignNullIfEmptied: true);
                // </06>
            }
    
            {
                // <07>
                string[]? array = { "A", "B", "C" };
                ArrayUtilities.RemoveAt(ref array, 1);
                // </07>
            }
    
            {
                // <08>
                string[] array = { "A", "B", "C" };
                array = ArrayUtilities.Without(array, "B");
                array = ArrayUtilities.Without(array, "c", comparer: StringComparer.InvariantCultureIgnoreCase);
                // </08>
            }
    
            {
                // <09>
                string[] array = { "A", "B", "C" };
                array = ArrayUtilities.WithoutAt(array, 1);
                // </09>
            }
    
            {
                // <10>
                string[] array = { "A", "B", "C" };
                array = ArrayUtilities.Without(array, "A");
                array = ArrayUtilities.Without(array, "B");
                array = ArrayUtilities.Without(array, "C", assignNullIfEmptied: true);
                // </10>
            }
    
            {
                // <11>
                string[] array = Array.Empty<string>();
                string[] array_ = (string[])ArrayUtilities.EmptyArray(typeof(string));
                // </11>
            }
    
            {
                // <12>
                string[] array = { "A", "B", "C", "D", "E", "F" };
                string[] slice = array.Slice(3, 3); // "D", "E", "F"
                // </12>
            }
    
            {
                // <13>
                string[] array = { "A", "B", "C", "D", "E", "F" };
                string[] subarray = { "D", "E", "F" };
                WriteLine(array.IndexOfSequence(subarray)); // 3
                // </13>
            }
    
            {
                // <14>
                string[] array = { "A", "B", "C", "D", "E", "F" };
                string[] subarray = { "A", "B", "C" };
                WriteLine(array.StartsWith(subarray)); // True
                // </14>
            }
    
            {
                // <15>
                int[,] matrix = new int[4, 4];
                matrix[0, 0] = 10;
                matrix = (int[,])ArrayUtilities.ArraySelect(matrix, (int x) => x * x);
                WriteLine(matrix[0, 0]); // 100
                // </15>
            }
    
            {
                // <16>
                int[,,] matrix = new int[3, 3, 3];
                IEnumerable<int> values = ArrayUtilities.Flatten<int>(matrix);
                // </16>
            }
    
            {
                // <17>
                int[,] matrix = new int[4, 4];
                foreach ((int[] indices, int value) in ArrayUtilities.VisitArray<int>(matrix))
                    WriteLine($"[{string.Join(", ", indices)}] = {value}"); // [0, 0] = 0
                // </17>
            }
    
            {
                // <18>
                int[,] matrix1 = new int[4, 4];
                int[,] matrix2 = new int[4, 4];
                foreach ((int[] indices, int value1, int value2) in ArrayUtilities.VisitArrays<int>(matrix1, matrix2))
                    WriteLine($"[{string.Join(", ", indices)}] = {value1} and {value2}"); // [0, 0] = 0 and 0
                // </18>
            }
    
            {
                // <19>
                object[] array = { new object(), "Hello", "World", 5, true };
                string[] strings = array.GetInstancesOf<object, string>();
                int[] ints = array.GetInstancesOf<object, int>();
                bool[] bools = array.GetInstancesOf<object, bool>();
                object[] objs = array.GetInstancesOf<object, object>(); // object, "Hello", "World", 5, true
                // </19>
            }
            {
                // <20>
                object[] array = { new object(), "Hello", "World", 5, true };
                string firstString = array.GetFirstInstanceOf<object, string>();     // "Hello"
                int firstInt = array.GetFirstInstanceOf<object, int>();              // 5
                bool firstBool = array.GetFirstInstanceOf<object, bool>();           // true
                // </20>
            }
            {
                // <21>
                object[] array = { new object(), "Hello", "World", 5, true };
                if (array.TryGetFirstInstanceOf(out string firstString)) WriteLine(firstString); // "Hello"
                // </21>
            }
    
        }
    }
    
    
    In This Article
    Back to top Copyright © Toni Kalajainen