Extension methods for IEnumerable & IList objects
Posted May 13, 2009
on:///<summary> ///Extention Method For IEnumerable Objects that returns random items from the source ///</summary> ///<typeparam name=”T”>Type of objects in array</typeparam> ///<param name=”source”>IEnumerable source(items in source must be of type T)</param> ///<param name=”howMany”>Number of items toreturn</param> ///<returns>Randomly returns a List T of specified number of items inthe IEnumerable source</returns> public static List<T>TakeRandom<T>(this IEnumerable<T> source,int howMany) { //if the source object is null the function return a new List<T> if(source ==null) return new List<T>(); var array = source.ToArray(); Random random =new Random(); for(vari = 0; i <Math.Min(howMany,array.Length); i++) { var currentItem = random.Next(i, array.Length); var temp = array[i]; array[i] = array[currentItem]; array[currentItem] = temp; } return array.Take<T>(howMany).ToList(); } ///<summary> ///Extension method for IEnumerable objects that return an item randomly chosen from the source ///</summary> ///<typeparam name=”T”>Type of object contained in the source</typeparam> ///<param name=”source”>IEnumerable source that contains many T objects</param> ///<returns>Returns an item of type T</returns> public staticT TakeRandom<T>(this IEnumerable<T> source) { //if the IEnumerable source object is null the function returns the default(T) if (source ==null) return default(T); List<T> list = TakeRandom(source, 1); T objectToReturn =default(T); if (list !=null) if (list.Count > 0) objectToReturn = list[0]; return objectToReturn; } ///<summary> ///Extension Method for IEnumerable object that returns if the collection is Empty ///</summary> ///<typeparam name=”T”></typeparam> ///<param name=”source”>IEnumerable object</param> ///<returns>Returns true if there is no items in the collection</returns> public static bool IsEmpty<T>(this IEnumerable<T> source) { if (source ==null) return true; else return source.Count() == 0 ?true:false; } ///<summary> ///Extension method for objects that implement the IList interface ///This method update an item from the list with a new one /////TODO: maybe add the predicate in the function itself to find if oldItem has a match in the list ///</summary> ///<typeparam name=”T”>T of objects in the List</typeparam> ///<param name=”source”>Source List (must implement IList)</param> ///<param name=”oldItem”>Old Item T to find and update</param> ///<param name=”newIitem”>New Item T</param> public static void Update<T>(this IList<T> source,T oldItem, T newIitem) { if (source !=null) { for (inti = 0; i <= source.Count() – 1; i++) { if (source[i].ToString() == oldItem.ToString()) { source[i] = newIitem; //once the item is found, exit the function break; } } } }
Tags: .Net
Leave a comment