jsg jsg - 3 months ago 27
C# Question

Select Method find one below and one above using Linq

Sorry if the question title may seem confusing. Basically I've created a list in MVC, which contains an ID, int Position and a string URL. With the list I want to be able to create a previous and next buttons, whilst using the list ID and position to get the buttons links.

If this makes no sense please let me know.

So basically once you click on a page, there will be a list of alternative pages, position will be created using a counter, Id will represent the page ID and the URL will be used for the buttons. I want to be able to use a linq or a c# statement that will be able to match the current page Id, with the page Id in the list, but then collect the item before and after using the position int value.

Here's my model

public Guid Id { get; set; }
public int Position { get; set; }
public string Url { get; set; }


That model is being used as a
List<overviewModel>


This what i thought it might start with

var selectedItem = overviewModel.Select(x => x.Id == PageId);


The list output will look like this

[0] id=xxx1, position = 0, url = /1
[1] id=xxx2, position = 1, url = /2
[2] id=xxx3, position = 2, url = /3
[3] id=xxx4, position = 3, url = /4


Let say i go to page
[1] id=xxx2, position = 1, url = /2


the before values I want to pull through is
[0] id=xxx1, position = 0, url = /1


the after values I want to pull through is
[2] id=xxx3, position = 2, url = /3

Answer

You can use IndexOf method on a new list that has been sorted by your Position value to get the index of the current item and then add 1 for the next or substract one for the previous item:

List<overviewModel> sortedOverviewModelList = overviewModelList.OrderBy(item => item.Position).ToList();
overviewModel selectedItem = sortedOverviewModelList.Select(x => x.Id == PageId);
int index = sortedOverviewModelList.IndexOf(selectedItem);
int nextitem = index+1;
int previtem = index-1;

You should add some checks that the Indexes are still within the list's bounds.