Created
December 2, 2011 17:19
-
-
Save nekman/1424043 to your computer and use it in GitHub Desktop.
C# collection mapper class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
namespace Utils.Lab.Mapping | |
{ | |
/// <summary> | |
/// Mapper class converts a collection with the given predicate. | |
/// </summary> | |
public class CollectionMapper | |
{ | |
private readonly bool _filterNull; | |
public CollectionMapper(bool filterNull) | |
{ | |
_filterNull = filterNull; | |
} | |
public CollectionMapper() : this(filterNull:false) | |
{ | |
} | |
public IEnumerable<TResult> ToCollection<TSource, TResult>(IEnumerable<TSource> collection, Func<TSource, TResult> predicate) where TSource : class | |
{ | |
return ToCollectionInternal(collection, predicate); | |
} | |
public IList<TResult> ToCollection<TSource, TResult>(IList<TSource> collection, Func<TSource, TResult> predicate) where TSource : class | |
{ | |
return ToCollectionInternal(collection, predicate).ToList(); | |
} | |
public ICollection<TResult> ToCollection<TSource, TResult>(ICollection<TSource> collection, Func<TSource, TResult> predicate) where TSource : class | |
{ | |
return ToCollectionInternal(collection, predicate).ToList(); | |
} | |
private IEnumerable<TResult> ToCollectionInternal<TSource, TResult>(IEnumerable<TSource> collection, Func<TSource, TResult> predicate) where TSource : class | |
{ | |
Validate(collection, predicate); | |
if (_filterNull) | |
{ | |
return collection.Where(item => item != null).Select(predicate); | |
} | |
return collection.Select(predicate); | |
} | |
private static void Validate(object entitiy, object predicate) | |
{ | |
if (entitiy == null) | |
{ | |
throw new ArgumentNullException("entitiy"); | |
} | |
if (predicate == null) | |
{ | |
throw new ArgumentNullException("predicate"); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment