Adds elements to dictionary from collection. - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:IDictionary

Description

Adds elements to dictionary from collection.

Demo Code

//   Copyright (c) Daniel Dabrowski - rod.42n.pl. All rights reserved.
using global::System.Collections.Generic;
using global::System.Collections;
using global::System;

public class Main{
        /// <summary>
        /// Adds elements to dictionary from collection.
        /// </summary>
        /// <typeparam name="K">The type of the key.</typeparam>
        /// <typeparam name="T">The type of the value.</typeparam>
        /// <param name="dictionary">The target dictionary.</param>
        /// <param name="source">The collection source.</param>
        /// <param name="nonUnique">The collection for non unique items. This collection must be empty.</param>
        /// <param name="keyExtractor">Delegate for pointing key value.</param>
        public static void AddToDictionaryFromCollection<K, T>(
            IDictionary<K, T> dictionary,
            ICollection<T> source,
            ICollection<T> nonUnique,
            Converter<T, K> keyExtractor)
        {//from  w ww . j  a v  a2s . c  om
            if (dictionary == null)
            {
                throw new ArgumentNullException("dictionary");
            }

            if (nonUnique == null)
            {
                throw new ArgumentNullException("nonUnique");
            }

            if (nonUnique.Count > 0)
            {
                throw new ArgumentException("nonUnique must be empty");
            }

            var isSourceCameEmpty = dictionary.Count == 0;
            var tempDict = isSourceCameEmpty ? dictionary : new Dictionary<K, T>();
            var nonUniqueKeys = new Dictionary<K, K>();

            foreach (var item in source)
            {
                var key = keyExtractor(item);
                if (!tempDict.ContainsKey(key))
                {
                    tempDict.Add(key, item);
                }
                else
                {
                    nonUnique.Add(item);
                    if (!nonUniqueKeys.ContainsKey(key))
                    {
                        nonUniqueKeys.Add(key, key);
                    }
                }
            }

            if (nonUnique.Count > 0)
            {
                foreach (var item in nonUniqueKeys.Keys)
                {
                    nonUnique.Add(tempDict[item]);
                    tempDict.Remove(item);
                }
            }

            if (isSourceCameEmpty)
            {
                return;
            }

            foreach (var item in tempDict)
            {
                if (dictionary.ContainsKey(item.Key))
                {
                    nonUnique.Add(item.Value);
                }
                else
                {
                    dictionary.Add(item);
                }
            }
        }
}

Related Tutorials