Posts Tagged ‘ Extension Methods ’

ObservableCollection – Extension Methods

When you ever used the CollectionView of the ObservableCollection and wanted to get or set the CurrentItem you might have noticed that it requires much more typing than expected.

For that purpose I created the following extension methods for the ObservableCollection.

 

  public static class CollectionExtensions
  {
    /// <summary>
    /// This method returns the current item of the given collection.
    /// </summary>
    /// <typeparam name="T">The type of the elements in the collection.</typeparam>
    /// <param name="source">The collection.</param>
    public static T GetCurrentItem<T>(this IEnumerable<T> source)
    {
      if (source == null)
        return default(T);
      var collectionView = CollectionViewSource.GetDefaultView(source);
      return (T)collectionView.CurrentItem;
    }

    /// <summary>
    /// This method returns the current position within the given collection.
    /// </summary>
    /// <typeparam name="T">The type of the elements in the collection.</typeparam>
    /// <param name="source">The collection.</param>
    public static int GetCurrentPosition<T>(this IEnumerable<T> source)
    {
      if (source == null)
        return -1;
      var collectionView = CollectionViewSource.GetDefaultView(source);
      return collectionView.CurrentPosition;
    }

    /// <summary>
    /// This method sets the current item of the given collection.
    /// </summary>
    /// <typeparam name="T">The type of the elements in the collection.</typeparam>
    /// <param name="source">The collection.</param>
    /// <param name="item">The item which should be set as the current one.</param>
    public static void SetCurrentItem<T>(this IEnumerable<T> source, T item)
    {
      if (source == null) return;
      var collectionView = CollectionViewSource.GetDefaultView(source);
      collectionView.MoveCurrentTo(item);
    }

    /// <summary>
    /// This method moves the current item to the first.
    /// </summary>
    /// <typeparam name="T">The type of the elements in the collection.</typeparam>
    /// <param name="source">The collection.</param>
    public static void MoveCurrentToFirst<T>(this IEnumerable<T> source)
    {
      if (source == null) return;
      var collectionView = CollectionViewSource.GetDefaultView(source);
      collectionView.MoveCurrentToFirst();
    }

    /// <summary>
    /// This method moves the current item to the previous.
    /// </summary>
    /// <typeparam name="T">The type of the elements in the collection.</typeparam>
    /// <param name="source">The collection.</param>
    public static void MoveCurrentToPrevious<T>(this IEnumerable<T> source)
    {
      if (source == null) return;
      var collectionView = CollectionViewSource.GetDefaultView(source);
      collectionView.MoveCurrentToPrevious();
    }

    /// <summary>
    /// This method moves the current item to the next.
    /// </summary>
    /// <typeparam name="T">The type of the elements in the collection.</typeparam>
    /// <param name="source">The collection.</param>
    public static void MoveCurrentToNext<T>(this IEnumerable<T> source)
    {
      if (source == null) return;
      var collectionView = CollectionViewSource.GetDefaultView(source);
      collectionView.MoveCurrentToNext();
    }

    /// <summary>
    /// This method moves the current item to the last.
    /// </summary>
    /// <typeparam name="T">The type of the elements in the collection.</typeparam>
    /// <param name="source">The collection.</param>
    public static void MoveCurrentToLast<T>(this IEnumerable<T> source)
    {
      if (source == null) return;
      var collectionView = CollectionViewSource.GetDefaultView(source);
      collectionView.MoveCurrentToLast();
    }

    /// <summary>
    /// This method sets the current position withing the given collection
    /// </summary>
    /// <typeparam name="T">The type of the elements in the collection</typeparam>
    /// <param name="source">The collection</param>
    /// <param name="index">The new position</param>
    public static void SetCurrentPosition<T>(this IEnumerable<T> source, int index)
    {
      if (source == null) return;
      var collectionView = CollectionViewSource.GetDefaultView(source);
      collectionView.MoveCurrentToPosition(index);
    }

    /// <summary>
    /// Removes the items from the collection according to the predicate.
    /// </summary>
    /// <param name="source">The source.</param>
    /// <param name="predicate">The predicate.</param>
    public static void Remove<T>(this ICollection<T> source, Func<T, bool> predicate)
    {
      if (source == null) return;
      var itemsToRemove = source.Where(predicate).ToList();
      foreach (var item in itemsToRemove)
        source.Remove(item);
    }
}
Advertisements

Extension Methods

Extension Methods are a nice way to add some extra functionality to a already existing class.
I use them for several tasks which are needed quite often. Such as the “raising” of an event or just the running of an action in the correct thread.
Therefore I decided to post the most important Extension Methods here.

When “raising” (fire) an event it is really annoying that we always have to check if the event is not null.
This results in a quite long code and we have always to repeat the same thing again.

Example:

public event EventHandler<EventArgs> MyEvent;

protected void RaiseMyEvent()
{
   if(MyEvent != null)
      MyEvent(this, EventArgs.Empty);
}

Using this extension method

/// <summary>
/// This method raises the given event with the given sender and EventArgs
/// </summary>
/// <typeparam name="T">The type of the event handler</typeparam>
/// <param name="eventHandler">The event handler</param>
/// <param name="sender">The sender</param>
/// <param name="e">The event args</param>
public static void Raise<T>(this EventHandler<T> eventHandler, Object sender, T e) where T : EventArgs
{
	if (eventHandler != null)
	{
		eventHandler(sender, e);
	}
}

it is possible to raise the event with that

public event EventHandler MyEvent<EventArgs>;

MyEvent.Raise(this, EventArgs.Empty);

Another example where Extension Methods are really useful is when you want to ensure that an action / function is executed in the right thread.
Usually you have to check whether you actually are in the right thread and invoke if necessary.

example:

public void MyMethod()
{
     if(myDispatcher.CheckAccess())
     {
        DoSomething();
     }
     else
     {
        myDispatcher.Invoke(new Action(MyMethod));
     }
}

In order to reduce this “useless” code we can use the following extension method

		/// <summary>
		/// This method automatically executes the given action in
		/// the correct thread.
		/// </summary>
		/// <param name="source">The source of the method call</param>
		/// <param name="func">The function which should be executed in the right thread</param>
		public static void Dispatch(this Dispatcher source, Action func)
		{
			if (source.CheckAccess())
				func();
			else
				source.Invoke(func);
		}

And here an example how to call it

myDispatcher.Dispatch(DoSomething);

More useful extension methods will follow…