If you want to limit the number of items returned in the result set when using ToList()
, you can use the Take
() method in your LINQ query.
The Take
method uses a specific number of elements from the start of a sequence, like this:
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
using (var db = new PersoneltrackingContext())
{
int numberOfItemsToTake = 10; // number of items to take
var result = (
from position in db.Position
join department in db.Department on position.DepartmentId equals department.Id
select new PositionDto
{
PositionID = position.PositionID,
PositionName = position.PositionName,
DepartmentId = position.DepartmentId,
DepartmentName = department.DepartmentName
}
).Take(numberOfItemsToTake).ToList();
foreach (var positionDto in result)
{
Console.WriteLine($"PositionID: {positionDto.PositionID}, PositionName: {positionDto.PositionName}, DepartmentId: {positionDto.DepartmentId}, DepartmentName: {positionDto.DepartmentName}");
}
}
}
}
public class PositionDto
{
public int PositionID { get; set; }
public string PositionName { get; set; }
public int DepartmentId { get; set; }
public string DepartmentName { get; set; }
}