To Hash Set - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:HashSet

Description

To Hash Set

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 HashSet<TKey> ToHashSet<TItem, TKey>(this IEnumerable<TItem> list, Func<TItem, TKey> keyFunc) where TKey : IComparable<TKey>
        {//from w w w. ja va  2  s.  com
            var res = new HashSet<TKey>();

            foreach (var item in list)
            {
                res.Add(keyFunc(item));
            }

            return res;
        }
        public static HashSet<TItem> ToHashSet<TItem>(this IEnumerable<TItem> list, bool ignoreDup) where TItem : IComparable<TItem>
        {
            var res = new HashSet<TItem>();

            foreach (var item in list)
            {
                if (ignoreDup && res.Contains(item))
                    continue;

                res.Add(item);
            }

            return res;
        }
        public static HashSet<TItem> ToHashSet<TItem>(this IEnumerable<TItem> list) where TItem: IComparable<TItem>
        {
            var res = new HashSet<TItem>();

            foreach (var item in list)
            {
                res.Add(item);
            }

            return res;
        }
        public static bool Contains<T>(this IEnumerable<T> me, Predicate<T> condition)
        {
            foreach (var val in me)
            {
                if (condition(val)) 
                    return true;
            }
            return false;
        }
}

Related Tutorials