Skip to content

Instantly share code, notes, and snippets.

@nekman
Created December 2, 2011 17:19
Show Gist options
  • Save nekman/1424043 to your computer and use it in GitHub Desktop.
Save nekman/1424043 to your computer and use it in GitHub Desktop.
C# collection mapper class
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