Showing posts with label LINQ. Show all posts
Showing posts with label LINQ. Show all posts

Tuesday, 22 September 2020

C# LINQ - Partitioning the List Collection Into Chunks

















Partitioning is the key part while working with the large collections in programming. LINQ helps in dividing the huge collection into chunks. 

Below code snippet takes the list and the chunk size and yields the chunks from the collection.

public static IEnumerable<List<T>> Partition<T>(List<T> source, Int32 size)
{
    for (int i = 0; i < Math.Ceiling(source.Count / (Double)size); i++)
        yield return new List<T>(source.Skip(size * i).Take(size));
}

Test Results:





Thursday, 12 December 2019

C# - Read AppSettings / Configuration Settings from File

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
/// <summary>
/// Reads the app settings kyes information for the provided keys
/// </summary>
/// <param name="filePath"></param>
/// <param name="keysToRead"></param>
/// <returns></returns>
private Dictionary<string, string> ReadAppSettings(string filePath, IEnumerable<string> keysToRead)
{
    JObject appsettingsInfo = JsonConvert.DeserializeObject<JObject>(File.ReadAllText(filePath));
        return appsettingsInfo.Root.Values().
                        Select(item => new { Key = item.Path, Value = item.Value<string>() }).
                        Where(item => keysToRead.Contains(item.Key, StringComparer.InvariantCultureIgnoreCase)).
                        Select(item => new KeyValuePair<string, string>(item.Key, item.Value)).ToDictionary(x => x.Key, x => x.Value);
}

Wednesday, 11 December 2019

C# - LINQ - How to Group List and Convert to Dictionary

 Dictionary<string, List<EmployeeDetails>> result = employeeInfo
                    .GroupBy(empInfo => empInfo.EmployeeName)
                    .ToDictionary(empInfo => empInfo.Key, empInfo => empInfo.ToList());