Files
jdescopingtool/OLD/DataModel/Helpers/LinqHelpers.cs
T
Joseph Doherty 26ff8d9b4f Initial commit: JDE Scoping Tool migration project
Set up repository with legacy .NET Framework 4.8 source (OLD/),
new .NET 10 Blazor solution (NEW/), OpenSpec specifications,
documentation, and project configuration.
2026-01-02 07:43:29 -05:00

60 lines
2.0 KiB
C#
Executable File

using System;
using System.Collections.Generic;
namespace DataModel.Helpers
{
/// <summary>
/// LINQ helper methods
/// </summary>
public static class LinqHelpers
{
/// <summary>
/// Filters for distinct elements by given key
/// </summary>
/// <typeparam name="TSource">Source data type</typeparam>
/// <typeparam name="TKey">Key data type</typeparam>
/// <param name="source">Source data</param>
/// <param name="keySelector">Key value function</param>
/// <returns>Distinct elements from source</returns>
public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
HashSet<TKey> keys = new HashSet<TKey>();
foreach (TSource element in source)
{
if (keys.Add(keySelector(element)))
{
yield return element;
}
}
}
/// <summary>
/// Groups the data into batches of give size
/// </summary>
/// <typeparam name="T">Data type of data</typeparam>
/// <param name="allData">Data to break into batches</param>
/// <param name="batchSize">Size of batches to create</param>
/// <returns>Enumerable collection of batches to process</returns>
public static IEnumerable<List<T>> BatchGroup<T>(this IEnumerable<T> allData, int batchSize)
{
List<T> batchGroup = new List<T>();
//Loop through data and group into batches
foreach (T data in allData)
{
batchGroup.Add(data);
if (batchGroup.Count == batchSize)
{
//Return batch of data
yield return batchGroup;
batchGroup = new List<T>();
}
}
//Return remaining data
yield return batchGroup;
}
}
}