Abhijeet_IXR
Abhijeet_IXR

Reputation: 947

Re-Arrange items In a list In C#

Basically, I am trying to return a list of imageURL for image slideshow whenever a user clicks on any image under a project.

I have worked upto a list which contains imageID and ImageUrl is returned according to projectId, imageid, passed in:

List<ProjectImageBO> pi = pd.GetProjectImagesByProjectID(projectId, imageid, pageno);

I want to re-arrange the returned list items in order something like this:

original list returned: <1Item, 2Item ,3Item ,4Item ,5Item>

if user has passed 3 as parameter for imageid in:

pd.GetProjectImagesByProjectID(projectId, imageid, pageno) 

then the returned list should be arranged as: <3Item ,4Item ,5Item ,1Item ,2ItemIte>.

I have worked up to:

public List<ProjectImageBO> GetListOfImagesByProjectPagination(int projectId, int imageid, int pageno)
    {
        ProjectImageDAL pd = new ProjectImageDAL();
        List<ProjectImageBO> pi = pd.GetProjectImagesByProjectID(projectId, imageid, pageno);
        if (imageid != 0)
        {
            var index = pi.FindIndex(x => x.ImageID == imageid);
            if (index != null)
            {
                if (index > 0)
                {
                    var item = pi[index];
                    pi[index] = pi[0];
                    pi[0] = item;
                }
            }
        }          
        return pi;
    }

which is simply swapping items in list like: <3Item, 2Item, 1Item, 4Item, 5Item> - which is not what I require. Any Suggestions or Sample Code ??

Upvotes: 0

Views: 309

Answers (2)

Dbuggy
Dbuggy

Reputation: 911

Something like this ? Items is the original list.

int idx = 2;
return items.Skip(idx).Union(items.Take(idx)).ToList();

Upvotes: 1

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37000

Well, I guess you can use a combination of Skip and Take:

var result = new List<ProjectImageBO>();
var tmp = // get the whole list before
// get the last three items:
result.AddRange(tmp.Skip(imageID - 1));
// get the first two items
result.AddRange(tmp.Take(imageID - 1));

Upvotes: 0

Related Questions