I have a requirement where I need to group records. For example I have 150 records and I need to get them in 5 groups, 30 records in each group.
Can anyone let me know how can I accomplish this?
Thanks in advance.
I have a requirement where I need to group records. For example I have 150 records and I need to get them in 5 groups, 30 records in each group.
Can anyone let me know how can I accomplish this?
Thanks in advance.
var groups = myRecords.Select((e, i) => new { Item = e, Grouping = (i / 5) }).GroupBy(e => e.Grouping);
var g1 = records.Take(30);
var g2 = records.Skip(30).Take(30);
...
If numbers 150 and 30 are just an example then you can easily put Skip(pageIndex*pageSize).Take(pageSize) in a loop.
If there's no specific group by property and just want them in specific size then this:
static class LinqExtensions
{
public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> list, int parts)
{
int i = 0;
var splits = from item in list
group item by i++ % parts into part
select part.AsEnumerable();
return splits;
}
}
Thanx to Hassan Kahn
suppose you have a list name EmployeeList having different departments. so you need to group them by Employee Department
public class Employee
{
public string Name { get; set; }
public string Department { get; set; }
}
public class EmployeeDepartMentList
{
public string DepartMentName {get;set; }
public List<Employee> EmployeeList { get; set; }
}
public class FinalResult
{
public List<EmployeeDepartMentList> GetEmployeesByDepartment()
{
List<Employee> EmployeeList = new List<Employee>();
var Model = EmployeeList.Select(x => x.Department).Distinct().Select(x => new EmployeeDepartMentList
{
DepartMentName = x,
EmployeeList = EmployeeList.Where(y => y.Department == x).ToList()
}).ToList();
return Model;
}
}