• 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

    EnumerableExtensions

    .AddRange(enumerable) adds elements to collection.

    HashSet<int> collection = new HashSet<int>();
    int[] elementsToAdd1 = { 1, 2, 3 };
    collection.AddRange(elementsToAdd1);
    

    .AddIfNew(element, comparer?) adds an element to collection if it doesn't already exist.

    List<string> lines = new List<string> { "Hello", "World" };
    lines.AddIfNew("Hello");
    WriteLine(lines.Count); // 2
    

    .AppendIfNew(element) returns a new enumerable where 'element' is appended if it didn't already exist.

    List<string> lines = new List<string> { "Hello", "World" };
    IEnumerable<string> enumr = lines.AppendIfNew("Hello").AppendIfNew("Bye");
    // "Hello", "World", "Bye"
    

    .AppendIfNew(enumerable) returns a new enumerable where another 'enumerable' is appended for all elements that didn't already exist.

    List<string> lines = new List<string> { "Hello", "World" };
    string[] elementsToAdd = { "Hello", "World", "Bye" };
    IEnumerable<string> enumr = lines.AppendIfNew(elementsToAdd);
    // "Hello", "World", "Bye"
    

    .ConcatToArray(enumerable) appends enumerable and returns an array. This is often more efficient than .Concat().ToArray() separately.

    List<string> lines1 = new List<string> { "Hello", "World" };
    List<string> lines2 = new List<string> { "More", "Lines" };
    string[] concat = lines1.ConcatToArray(lines2);
    

    .ConcatToArray(enumerable, enumerable) appends three enumerables and returns an array.

    List<string> lines1 = new List<string> { "Hello", "World" };
    List<string> lines2 = new List<string> { "More", "Lines" };
    List<string> lines3 = new List<string> { "ABC", "EFG" };
    string[] concat = lines1.ConcatToArray(lines2, lines3);
    

    .ConcatOptional(element?) returns an enumerable where element is appended if it is not null.

    string[] lines = new string[] { "Hello", "World" };
    IEnumerable<string> concat = lines.ConcatOptional(null);
    

    .ExceptValue(value, comparer?) returns an enumerable where specific value(s) are excluded.

    string[] lines = new string[] { "Hello", "World" };
    IEnumerable<string> enumr = lines.ExceptValue("Hello");
    

    .IsEmpty() tests whether enumerable is empty.

    string[] lines1 = new string[0];
    string[] lines2 = new string[] { "Hello", "World" };
    WriteLine(lines1.IsEmpty()); // True
    WriteLine(lines2.IsEmpty()); // False
    

    .AllTrue(selector) tests whether 'selector' is true for all elements.

    string[] lines = new string[] { "Hello", "Hallo" };
    WriteLine(lines.AllTrue((string s) => s[0] == 'H')); // True
    

    .SameValue(fallback?, comparer?) tests whether all elements have same value. If so, returns the value. If not returns 'fallback' value.

    string[] lines1 = new string[] { "Hello", "Hello" };
    string[] lines2 = new string[] { "Hello", "World" };
    WriteLine(lines1.SameValue()); // "Hello"
    WriteLine(lines2.SameValue()); // Null
    WriteLine(lines2.SameValue("Fallback")); // "Fallback"
    

    .IndexOf(selector) finds the first occurance of element where 'selector' returns true.

    string[] lines = new string[] { "Hello", "World" };
    WriteLine(lines.IndexOf((string s) => s == "World")); // 1
    

    .IndexOf(value, comparer?) finds the first occurance of element where comparer determines equality.

    string[] lines = new string[] { "Hello", "World" };
    WriteLine(lines.IndexOf("world", StringComparer.InvariantCultureIgnoreCase)); // 1
    

    .IndicesOf(value, comparer?) finds the all occurances of elements where comparer determines equality.

    string[] lines = new string[] { "Hello", "World", "world" };
    foreach (int index in lines.IndicesOf("World", StringComparer.InvariantCultureIgnoreCase))
        WriteLine(index); // 1, 2
    

    .CompareEquality(enumerator, comparer?) compares all elements for equality of two enumerable.

    string[] lines1 = new string[] { "Hello", "World" };
    string[] lines2 = new string[] { "Hello", "World" };
    WriteLine(lines1.CompareEquality(lines2)); // True
    WriteLine(lines1.CompareEquality(lines2, StringComparer.InvariantCultureIgnoreCase)); // True
    

    .CompareOrder(enumerator, comparer?) compares all elements for order of two enumerable.

    string[] lines1 = new string[] { "Hello", "World" };
    string[] lines2 = new string[] { "Hello", "World" };
    WriteLine(lines1.CompareOrder(lines2)); // 0
    WriteLine(lines1.CompareOrder(lines2, StringComparer.InvariantCultureIgnoreCase)); // 0
    

    .HashElements() calculates hashcode of all elements.

    string[] lines = new string[] { "Hello", "World" };
    WriteLine(lines.HashElements());
    

    .OrderByFrequency(comparer?) orders elements by frequency, highest frequency first.

    string[] lines = new string[] { "1", "2", "3", "2", "3", "2"  };
    IEnumerable<string> byFrequency = lines.OrderByFrequency();
    WriteLine(String.Join(", ", byFrequency)); // "2, 3, 1"
    

    Full Example

    Full example
    using System;
    using System.Collections.Generic;
    using Avalanche.Utilities;
    using static System.Console;
    
    public class enumerableextensions
    {
        public static void Run()
        {
            {
                int[] array = { 1, 2, 3 };
            }
            {
                // <01>
                HashSet<int> collection = new HashSet<int>();
                int[] elementsToAdd1 = { 1, 2, 3 };
                collection.AddRange(elementsToAdd1);
                // </01>
            }
            {
                // <02>
                List<string> lines = new List<string> { "Hello", "World" };
                lines.AddIfNew("Hello");
                WriteLine(lines.Count); // 2
                // </02>
            }
            {
                // <03>
                List<string> lines = new List<string> { "Hello", "World" };
                IEnumerable<string> enumr = lines.AppendIfNew("Hello").AppendIfNew("Bye");
                // "Hello", "World", "Bye"
                // </03>
            }
            {
                // <04>
                List<string> lines = new List<string> { "Hello", "World" };
                string[] elementsToAdd = { "Hello", "World", "Bye" };
                IEnumerable<string> enumr = lines.AppendIfNew(elementsToAdd);
                // "Hello", "World", "Bye"
                // </04>
            }
            {
                // <05>
                List<string> lines1 = new List<string> { "Hello", "World" };
                List<string> lines2 = new List<string> { "More", "Lines" };
                string[] concat = lines1.ConcatToArray(lines2);
                // </05>
            }
            {
                // <06>
                List<string> lines1 = new List<string> { "Hello", "World" };
                List<string> lines2 = new List<string> { "More", "Lines" };
                List<string> lines3 = new List<string> { "ABC", "EFG" };
                string[] concat = lines1.ConcatToArray(lines2, lines3);
                // </06>
            }
            {
                // <07>
                string[] lines = new string[] { "Hello", "World" };
                IEnumerable<string> concat = lines.ConcatOptional(null);
                // </07>
            }
            {
                // <08>
                string[] lines = new string[] { "Hello", "World" };
                IEnumerable<string> enumr = lines.ExceptValue("Hello");
                // </08>
            }
            {
                // <09>
                string[] lines1 = new string[0];
                string[] lines2 = new string[] { "Hello", "World" };
                WriteLine(lines1.IsEmpty()); // True
                WriteLine(lines2.IsEmpty()); // False
                // </09>
            }
            {
                // <10>
                string[] lines = new string[] { "Hello", "Hallo" };
                WriteLine(lines.AllTrue((string s) => s[0] == 'H')); // True
                // </10>
            }
            {
                // <11>
                string[] lines1 = new string[] { "Hello", "Hello" };
                string[] lines2 = new string[] { "Hello", "World" };
                WriteLine(lines1.SameValue()); // "Hello"
                WriteLine(lines2.SameValue()); // Null
                WriteLine(lines2.SameValue("Fallback")); // "Fallback"
                // </11>
            }
            {
                // <12>
                string[] lines = new string[] { "Hello", "World" };
                WriteLine(lines.IndexOf((string s) => s == "World")); // 1
                // </12>
            }
            {
                // <13>
                string[] lines = new string[] { "Hello", "World" };
                WriteLine(lines.IndexOf("world", StringComparer.InvariantCultureIgnoreCase)); // 1
                // </13>
            }
            {
                // <14>
                string[] lines = new string[] { "Hello", "World", "world" };
                foreach (int index in lines.IndicesOf("World", StringComparer.InvariantCultureIgnoreCase))
                    WriteLine(index); // 1, 2
                // </14>
            }
            {
                // <15>
                string[] lines1 = new string[] { "Hello", "World" };
                string[] lines2 = new string[] { "Hello", "World" };
                WriteLine(lines1.CompareEquality(lines2)); // True
                WriteLine(lines1.CompareEquality(lines2, StringComparer.InvariantCultureIgnoreCase)); // True
                // </15>
            }
            {
                // <16>
                string[] lines1 = new string[] { "Hello", "World" };
                string[] lines2 = new string[] { "Hello", "World" };
                WriteLine(lines1.CompareOrder(lines2)); // 0
                WriteLine(lines1.CompareOrder(lines2, StringComparer.InvariantCultureIgnoreCase)); // 0
                // </16>
            }
            {
                // <17>
                string[] lines = new string[] { "Hello", "World" };
                WriteLine(lines.HashElements());
                // </17>
            }        
            {
                // <18>
                string[] lines = new string[] { "1", "2", "3", "2", "3", "2"  };
                IEnumerable<string> byFrequency = lines.OrderByFrequency();
                WriteLine(String.Join(", ", byFrequency)); // "2, 3, 1"
                // </18>
            }
        }
    }
    
    
    In This Article
    Back to top Copyright © Toni Kalajainen