• 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

    BijectionMap

    BijectionMap<L, R> is a map that holds 1:1 correspondence between left and right sides.

    var map = new BijectionMap<string, int>();
    

    BijectionMap.Create(leftType, rightType) creates with type arguments.

    var map =
        (BijectionMap<string, int>)
        BijectionMap.Create(typeof(string), typeof(int));
    

    BijectionMap can be constructed with explicit comparers.

    IEqualityComparer<string> leftComparer = StringComparer.InvariantCultureIgnoreCase;
    IEqualityComparer<int> rightComparer = EqualityComparer<int>.Default;
    var map = new BijectionMap<string, int>(leftComparer, rightComparer);
    
    IEqualityComparer<string> leftComparer = StringComparer.InvariantCultureIgnoreCase;
    IEqualityComparer<int> rightComparer = EqualityComparer<int>.Default;
    var map = BijectionMap.Create(typeof(string), typeof(int), leftComparer, rightComparer);
    

    BijectionMap can be constructed with IEnumerable<KeyValuePair<L, R>> initialization values.

    var dictionary = new Dictionary<string, int> { { "Hello", 123 } };
    var map = new BijectionMap<string, int>(dictionary);
    

    .AddAll(IEnumerable<KeyValuePair<L, R>>) adds from a source.

    var dictionary = new Dictionary<string, int> { { "Hello", 123 } };
    var map = new BijectionMap<string, int>()
        .AddAll(dictionary);
    

    .Put(L, R) puts a value pair to the map.

    var map = new BijectionMap<string, int>();
    map.Put("A", 1);
    map.Put("B", 2);
    map.Put("C", 3);
    

    .GetLeft(), .TryGetLeft(), .GetRight(), .TryGetRight() and R this[L] returns correlated value from the other side.

    int x = map["A"];
    string y = map.GetLeft(2);
    int z = map.GetRight("B");
    if (map.TryGetRight("C", out int value0)) WriteLine(value0); // 3
    if (map.TryGetLeft(2, out string? value1)) WriteLine(value1); // "B"
    

    .SetReadOnly() extension method of IReadOnly locks dictionary.

    map.SetReadOnly();
    

    After locking write throws InvalidOperationException.

    // Write
    try
    {
        map.Put("Key3", 99);
    }
    catch (InvalidOperationException)
    {
    }
    

    .Contains(L, R), .ContainsLeft(L), .ContainsRight(R) tests whether specific value exists in the map.

    WriteLine(map.Contains("A", 1)); // True
    WriteLine(map.Contains("A", 2)); // False
    WriteLine(map.ContainsLeft("A")); // True
    WriteLine(map.ContainsRight(3)); // True
    

    .RemoveWithLeft(L) and .RemoveWithRight(R) removes a pair with left and right keys.

    map.RemoveWithLeft("A");
    map.RemoveWithRight(2);
    

    .RetainAllLeft(IEnumerable<L>) and .RetainAllRight(IEnumerable<R>) retains values.

    map.RetainAllLeft(new string[] { "B", "C" });
    map.RetainAllRight(new int[] { 2, 3 });
    

    .GetRightSet(), .GetLeftSet(), .GetLeftToRightDictionary() and .GetRightToLeftDictionary() returns internal maps.

    ICollection<int> rightSet = map.GetRightSet();
    ICollection<string> leftSet = map.GetLeftSet();
    IDictionary<string, int> rightMap = map.GetLeftToRightDictionary();
    IDictionary<int, string> leftMap = map.GetRightToLeftDictionary();
    

    Full Example

    Full example
    using System;
    using System.Collections.Generic;
    using Avalanche.Utilities;
    using static System.Console;
    
    public class bijectionmap
    {
        public static void Run()
        {
            {
                // <01>
                var map = new BijectionMap<string, int>();
                // </01>
            }
            {
                // <02>
                var map =
                    (BijectionMap<string, int>)
                    BijectionMap.Create(typeof(string), typeof(int));
                // </02>
            }
    
            {
                // <03>
                IEqualityComparer<string> leftComparer = StringComparer.InvariantCultureIgnoreCase;
                IEqualityComparer<int> rightComparer = EqualityComparer<int>.Default;
                var map = new BijectionMap<string, int>(leftComparer, rightComparer);
                // </03>
            }
    
            {
                // <04>
                IEqualityComparer<string> leftComparer = StringComparer.InvariantCultureIgnoreCase;
                IEqualityComparer<int> rightComparer = EqualityComparer<int>.Default;
                var map = BijectionMap.Create(typeof(string), typeof(int), leftComparer, rightComparer);
                // </04>
            }
            {
                // <05>
                var dictionary = new Dictionary<string, int> { { "Hello", 123 } };
                var map = new BijectionMap<string, int>(dictionary);
                // </05>
            }
            {
                // <06>
                var dictionary = new Dictionary<string, int> { { "Hello", 123 } };
                var map = new BijectionMap<string, int>()
                    .AddAll(dictionary);
                // </06>
            }
    
            {
                // <07>
                var map = new BijectionMap<string, int>();
                map.Put("A", 1);
                map.Put("B", 2);
                map.Put("C", 3);
                // </07>
    
                // <08>
                int x = map["A"];
                string y = map.GetLeft(2);
                int z = map.GetRight("B");
                if (map.TryGetRight("C", out int value0)) WriteLine(value0); // 3
                if (map.TryGetLeft(2, out string? value1)) WriteLine(value1); // "B"
                // </08>
    
                // <09>
                map.SetReadOnly();
                // </09>
    
                // <10>
                // Write
                try
                {
                    map.Put("Key3", 99);
                }
                catch (InvalidOperationException)
                {
                }
                // </10>
            }
    
            {
                var map = new BijectionMap<string, int>();
                map.Put("A", 1);
                map.Put("B", 2);
                map.Put("C", 3);
                // <11>
                WriteLine(map.Contains("A", 1)); // True
                WriteLine(map.Contains("A", 2)); // False
                WriteLine(map.ContainsLeft("A")); // True
                WriteLine(map.ContainsRight(3)); // True
                // </11>
            }
    
            {
                var map = new BijectionMap<string, int>();
                map.Put("A", 1);
                map.Put("B", 2);
                map.Put("C", 3);
                // <12>
                map.RemoveWithLeft("A");
                map.RemoveWithRight(2);
                // </12>
            }
    
            {
                var map = new BijectionMap<string, int>();
                map.Put("A", 1);
                map.Put("B", 2);
                map.Put("C", 3);
                // <13>
                map.RetainAllLeft(new string[] { "B", "C" });
                map.RetainAllRight(new int[] { 2, 3 });
                // </13>
                foreach (var pair in map) WriteLine(pair);
            }
    
            {
                var map = new BijectionMap<string, int>();
                map.Put("A", 1);
                map.Put("B", 2);
                map.Put("C", 3);
                // <14>
                ICollection<int> rightSet = map.GetRightSet();
                ICollection<string> leftSet = map.GetLeftSet();
                IDictionary<string, int> rightMap = map.GetLeftToRightDictionary();
                IDictionary<int, string> leftMap = map.GetRightToLeftDictionary();
                // </14>
            }
        }
    }
    
    
    In This Article
    Back to top Copyright © Toni Kalajainen