Share via


Extensions I found useful while developing with WPF and LINQ to SQL

 

When I observe developers writing solutions using LINQ to SQL or Entity Framework, I see a number of conversions occurring time and time again. Below are some of the more trivial utility method extensions I used when developing solutions based on LINQ to SQL and WPF—simple as they are I found them useful in a variety of situations.

Extension to remove data from a collection using a predicate.

 public static void Remove<T>( this ICollection<T> data, Func<T, bool> predicate )
{
     if( predicate == null ) 
     {
          data.Clear(); 
     } 
     else 
     { 
         foreach( T item in data.Where( predicate )) 
         { 
               data.Remove( item ); 
         } 
     } 
} 

 

Converting an enumerable to an ObservableCollection for data binding

 public static ObservableCollection<T> ToObservableCollection<T>( this IEnumerable<T> collection ) 
{ 
    List<T> list = new List<T>( collection.Count() ); 
    using( IEnumerator<T> enumerator = collection.GetEnumerator() ) 
    { 
        while( enumerator.MoveNext() ) 
        { 
            list.Add( enumerator.Current ); 
        } 
    } 
    return new ObservableCollection<T>( list ); 
} 

The same but for a list

 public static ObservableCollection<T> ToObservableCollection<T>( this List<T> collection ) 
{ 
    return new ObservableCollection<T>( collection ); 
}