Split IEnumerable In Groups Removing Duplicates - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:IEnumerable

Description

Split IEnumerable In Groups Removing Duplicates

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 List<List<TSource>> SplitInGroupsRemovingDuplicates<TSource>(this IEnumerable<TSource> values, int groupSize)
        {// w w w  .  j  a  v a  2  s  .  c  o m
            var res = new List<List<TSource>>();

            var duplicateCheck = new HashSet<TSource>();
            var currentList = new List<TSource>(groupSize);

            foreach (var value in values)
            {
                if (duplicateCheck.Contains(value))
                    continue;

                duplicateCheck.Add(value);

                if (currentList.Count >= groupSize)
                {
                    res.Add(currentList);
                    currentList = new List<TSource>(groupSize);
                }
                currentList.Add(value);
            }

            if (currentList.Count > 0)
                res.Add(currentList);

            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