Scrape all of the items in the collection which are non null and unique. - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:ICollection

Description

Scrape all of the items in the collection which are non null and unique.

Demo Code


using System.Linq;
using System;//from  w  w  w.  j ava  2s.  c  om
using System.Collections.Generic;
using System.Collections;
using UnityEngine;

public class Main{
        /// <summary>
        /// Scrape all of the items in the collection which are non null and unique. 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="self"></param>
        /// <returns></returns>
        public static IEnumerable<T> ScrapeNonNullAndUniqueItems<T>(this IEnumerable<T> self)
        {
            if (self == null)
            {
                yield break;
            }

            HashSet<T> toReturn = new HashSet<T>();

            foreach (var item in self)
            {
                if (item == null)
                    continue;

                if (toReturn.Contains(item) == true)
                    continue;

                toReturn.Add(item);
            }

            foreach (var item in toReturn)
            {
                yield return item;
            }
        }
}

Related Tutorials