Skip to content

Instantly share code, notes, and snippets.

@Hallmanac
Created November 7, 2017 11:15
Show Gist options
  • Save Hallmanac/d3826a3b9097106d60496b6c0c605812 to your computer and use it in GitHub Desktop.
Save Hallmanac/d3826a3b9097106d60496b6c0c605812 to your computer and use it in GitHub Desktop.
Extension methods for the List<T> class in C#
using System.Linq;
using System.Linq.Expressions;
namespace System.Collections.Generic
{
public static class ListExtensions
{
/// <summary>
/// Takes the current list and returns a List of Lists. A.K.A. a batch of lists where each list is no larger than the
/// given <see cref="batchSize" />.
/// </summary>
/// <typeparam name="T">Generic type in the List</typeparam>
/// <param name="currentList">The current list that this method operates on.</param>
/// <param name="batchSize">The max number of items to be in each list.</param>
/// <returns></returns>
public static List<List<T>> ToBatch<T>(this List<T> currentList, int batchSize)
{
var batchList = new List<List<T>>();
var maxBatchCount = currentList.Count < batchSize ? currentList.Count : batchSize;
var currentCount = 0;
while (currentCount < currentList.Count)
{
var batch = new List<T>();
batch.AddRange(currentList.Skip(currentCount).Take(maxBatchCount).ToList());
batchList.Add(batch);
currentCount += maxBatchCount;
}
return batchList;
}
public static IQueryable<T> OrderByField<T>(this IQueryable<T> q, string sortField, bool ascending)
{
var param = Expression.Parameter(typeof(T), "p");
var prop = Expression.Property(param, sortField);
var exp = Expression.Lambda(prop, param);
var method = ascending ? "OrderBy" : "OrderByDescending";
var types = new[] {q.ElementType, exp.Body.Type};
var mce = Expression.Call(typeof(Queryable), method, types, q.Expression, exp);
return q.Provider.CreateQuery<T>(mce);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment