Useful list operations

I often find myself having to loop through a collection to perform some operations on its item. After a while I got bored writing foreach loops to do so, which is why I wrote a few extension methods to help me.

 public static class CollectionExtensions {

    public static void Apply<T, TG>(this IEnumerable<T> enumerable, Func<T, TG> func) {
      if (enumerable.IsNullOrEmpty()) return;

      foreach (var item in enumerable) {
        func(item);
      }
    }

    public static void Apply<T, TG>(this IEnumerable<T> enumerable, Func<T, TG> func, Func<T,bool> predicate )
    {
      if(enumerable.IsNullOrEmpty()) return;

      enumerable.Where(predicate).Apply(func);
    }

    public static bool IsNullOrEmpty<T>(this IEnumerable<T> enumerable) {
      return enumerable == null || enumerable.Count() == 0;
    }

    public static void RemoveNulls<T>(this IList<T> items) where T : class {
      if (IsNullOrEmpty(items)) return;

      var i = 0;
      while (i < items.Count) {
        if (items[i] == null) {
          items.RemoveAt(i);
        }
        else {
          i++;
        }
      }
    }

  }

Now you, instead of using a foreach loop, I can do something like this:

var list = new List<Myclass> { new Myclass()};
      var element1 = "sss";
      list.Apply(e=> e.Element1=element1);

Or even this:

var list = new List<Myclass> { new Myclass(), new Myclass{Element1 = "ll"}};
      var element1 = "sss";
      list.Apply(e => e.Element1 = element1, t=> t.Element1.IsNullOrEmpty());

This class has been added to JourneyLib. I hope this helps another Journeyman out there.

Advertisements
Useful list operations

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s