To Dictionary Ignoring Duplicate Keys - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:IDictionary

Description

To Dictionary Ignoring Duplicate Keys

Demo Code


using System.Linq;
using System.Text;
using System.Globalization;
using System.ComponentModel;
using System.Collections.Generic;
using System.Collections;

public class Main{
        public static Dictionary<TKey, TValue> ToDictionaryIgnoringDuplicateKeys<TItem, TKey, TValue>(this IList<TItem> list, Func<TItem, TKey> keyFunc, Func<TItem, TValue> valueFunc)
        {/*  ww  w. j a  va  2s  .com*/
            var res = new Dictionary<TKey, TValue>(list.Count);

            foreach (var item in list)
            {
                var key = keyFunc(item);
                if (!res.ContainsKey(key))
                    res.Add(key, valueFunc(item));
            }

            return res;
        }
}

Related Tutorials