Broow Broow - 3 months ago 7
C# Question

My example and understanding of Skip and Take is correct?

Sorry for being beginner about this code below because i know about basics only.

var educ = (from a in db.RCEducationalBackgrounds
join b in db.RCPersonEducationalBackgrounds
on a.RCEducationalBackgroundId equals b.RCEducationalBackgroundId
where b.PersonId == PersonId
select new
{
a.RCEducationalBackgroundId,
a.EducationalLevelId,
a.EducationLevel.EducationLevelDesc,
b.RCEducationalBackground.School.SchooldName,
b.RCEducationalBackground.SchoolAddress,
a.Course,
a.EducationCollegeDegree.EducCollegeDegreeDesc,
a.YearGraduated,
a.AwardsReceived,
a.IDAFrom,
a.IDATo,
a.HighestGradeLevelUnitsEarned,
a.EducCollegeDegreeId,
a.SchoolId,
b.RCPersonEducationalBackgroundId,
b.IsValidated
});
int totalRecords = educ.Count();
//educ value is 7
var exams = educ.OrderBy(m => m.EducationalLevelId).Skip(0).Take(5);


So far as i understand about this code is it will take the first
5
numbers and skip no numbers.

About this second example

var educ = (from a in db.RCEducationalBackgrounds
join b in db.RCPersonEducationalBackgrounds
on a.RCEducationalBackgroundId equals b.RCEducationalBackgroundId
where b.PersonId == PersonId
select new
{
a.RCEducationalBackgroundId,
a.EducationalLevelId,
a.EducationLevel.EducationLevelDesc,
b.RCEducationalBackground.School.SchooldName,
b.RCEducationalBackground.SchoolAddress,
a.Course,
a.EducationCollegeDegree.EducCollegeDegreeDesc,
a.YearGraduated,
a.AwardsReceived,
a.IDAFrom,
a.IDATo,
a.HighestGradeLevelUnitsEarned,
a.EducCollegeDegreeId,
a.SchoolId,
b.RCPersonEducationalBackgroundId,
b.IsValidated
});
int totalRecords = educ.Count();
//educ value is 7
var exams = educ.OrderBy(m => m.EducationalLevelId).Skip(2).Take(5);


It will skip the first
2
numbers and start the count from number
3
?

UPDATED

as Sina Iravanian said.

Answer

You're using these in a wrong way !

First, Enumerable.Count() returns the numbers of elements after enumerating an IEnumearble.

This won't compile because .Count() returns a Number:

int count = sequence.Count().Skip(N).Take(M); // Error, Skip is not Defined for int/

This Compiles, but always returns M or less:

int count = sequence.Skip(N).Take(M).Count()

Skip N followed by Take M , takes at most M elements after skipping N elements. For example:

{ 1, 2, 3, 4, 5, 6 }

Result of sequence.Skip(2).Take(5) returns 4 elements because there is no more:

{ 3, 4, 5, 6 }

sequence.Skip(2).Take(5).Count() just returns the number of elements:

4

As a Conclusion:

  • Skip(N): Skips N elements and returns the rest (unless chained with other linq methods eg Take)
  • Take (N): Takes at most N elements and less if there is less than N.
  • Count(): Counts the elements and can't be chained (followed by) Skip or Take methods.