I have a list of ID numbers that I pull from a session variable and convert to an Array for use in a LINQ query that will then be used to populate a dropdown list. This is basically a list of recent clients that have been accessed by the program. I would like it to show them in the order they were last accessed.
Example array values (66, 78, 55, 24, 80)
After the LINQ query, it orders them by ID by default: (24, 55, 66, 78, 80)
So when it shows in the dropdownlist it is sorted this way when all I really needed was for it to stay in the order of the array values, only reversed: (80, 24, 55, 78, 66)
Code:
// Grab pre-built session variable with comma delimited int values
string RecentClients = Session["RecentClients"].ToString();
// Convert to Array
int[] RecentClientsArray =
Array.ConvertAll(RecentClients.Split(','), n => Convert.ToInt32(n));
// Display in gridview to see current order of array (For debug purposes)
gridArray.DataSource = RecentClientsArray;
gridArray.DataBind();
// Setup LINQ
DataClasses1DataContext db = new DataClasses1DataContext();
// Populate RecenClientList using RecentClientsArray to compare to ConsumerID
var RecentClientList =
(from c in db.ClientNames
where RecentClientsArray.Contains(c.ConsumerID)
select new { FullName = c.LastName + ", " + c.FirstName + " #" + c.ConsumerID,
recentConsumerID = c.ConsumerID});
// Display in gridview to see new order after populating var RecentClientList
// (for debug purposes)
gridList.DataSource = RecentClientList;
gridList.DataBind();
// Set and bind values for dropdown list.
ddLastClients.DataSource = RecentClientList;
ddLastClients.DataTextField = "FullName";
ddLastClients.DataValueField = "recentConsumerID";
ddLastClients.DataBind();
EDIT Corrected Code using accepted solution:
// Grab pre-built session variable with comma delimited int values
string RecentClients = Session["RecentClients"].ToString();
// Convert to Array
int[] RecentClientsArray = Array.ConvertAll(RecentClients.Split(','), n => Convert.ToInt32(n));
// Setup LINQ
DataClasses1DataContext db = new DataClasses1DataContext();
// Populate RecenClientList using RecentClientsArray to compare to ConsumerID
var RecentClientList = (from c in db.ClientNames
where RecentClientsArray.Contains(c.ConsumerID)
select new { FullName = c.LastName + ", " + c.FirstName + " #" + c.ConsumerID, recentConsumerID = c.ConsumerID });
var clients = (from item in RecentClientsArray
join client in RecentClientList.ToList()
on item equals client.recentConsumerID
select client).Reverse().Distinct();
// Set and bind values for dropdown list.
ddLastClients.DataSource = clients;
ddLastClients.DataTextField = "FullName";
ddLastClients.DataValueField = "recentConsumerID";
ddLastClients.DataBind();