Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
HI,

var abc = (from d in Model.Candidates select d.Candidate_ID).ToList();


In this var abc, i am getting 15 candidate Id's.
Now I need to split the 15 candidates into 3 parts and assign to 3 different Var's.

Please help me with the Linq queries.

What I have tried:

var abc = (from d in Model.Candidates select d.Candidate_ID).ToList();
Posted
Updated 11-Mar-20 21:31pm

1 solution

If i understand you well...

C#
var a1 = Model.Candidates
    .Select(d=> d.Candidate_ID)
    .Take(5)
    .ToList();

var a2 = Model.Candidates
    .Select(d=> d.Candidate_ID)
    .Skip(5)
    .Take(5)
    .ToList(); 

var a3 = Model.Candidates
    .Select(d=> d.Candidate_ID)
    .Skip(10)
    .Take(5)
    .ToList(); 


In case, you want to create custom pagination, you can achieve that by creating generic method. See:

C#
void Main()
{
	List<Candidate> Candidates = GetCandidates();
	
	int j = 5;
	for(int i = 0; i<Candidates.Count; i+=j)
	{
		var data = GetPortion<Candidate>(Candidates, d=>d.Candidate_ID, i, j).ToList();
		data.Dump();
	}
		
}

// Define other methods and classes here
class Candidate
{
	public Guid Candidate_ID {get; set;}
}

IEnumerable<T> GetPortion<T>(IEnumerable<T> list, Func<T, object> orderByField, int curr_val, int NoOfRecordsToGet) where T: class
{
	return list.OrderBy(orderByField).Skip(curr_val).Take(NoOfRecordsToGet);
}


List<Candidate> GetCandidates()
{
	List<Candidate> candies = new List<Candidate>();
	for(int i = 0; i<28; i++)
		candies.Add(new Candidate(){Candidate_ID = Guid.NewGuid()});
	return candies;
}
 
Share this answer
 
v4
Comments
Member 14196861 12-Mar-20 3:46am    
What if the Count is dynamic and changes
Maciej Los 12-Mar-20 3:53am    
If you want to get specific portion of data, you have to create custom method which will get as a parameter: 1) the number of data to get and 2) the number of data to skip. Then you'll need to create variables in a for(...) loop. That's all.
Maciej Los 12-Mar-20 4:02am    
See udated answer.
Member 14196861 12-Mar-20 4:03am    
The method 'Skip' is only supported for sorted input in LINQ to Entities. The method 'OrderBy' must be called before the method 'Skip'. - Stuck with this error from the code above
Maciej Los 12-Mar-20 4:16am    
See updated answer. I've improved generic method to sort data. See updated Main method also.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900