Reputation: 326
I have a list of integers ids
, from table i need to select details only for those whose ids are in the list, I have already done that
but i need that data sorted same way as they were in the list Explaination below:
List<int> SelectedUser = new List<int> { 26,1,22,27 };
List<ValidateDropDownBind> objValidateUserList = (from p in context.tblUser
join q in context.tblTaskReportingAuthority on p.UserID equals q.UserID into gj
from r in gj.DefaultIfEmpty()
where p.IsActive == true && p.CompanyID == CurrentAdminSession.CompanyID && SelectedUser.Contains(p.UserID)
//orderby r.TaskReportingAuthorityID
select new ValidateDropDownBind
{
value = p.UserID,
name = p.FirstName + " " + p.LastName
}).GroupBy(x => x.value, (key, group) => group.FirstOrDefault()).ToList();
Now, as i run this query i got the list of details from db but it is in sorted form but i need to sort them by the form which they were
in the list (SelectedUser).
Upvotes: 0
Views: 62
Reputation: 423
It is not too pretty but you could use your first list and then select from the second list with FirstOrDefault
.
The last Where
is to be sure you do not include nulls if the first SelectedUser
is not found in the objValidateUserList
list.
var sortedList = SelectedUser.Select(
sortedListUser => objValidateUserList.FirstOrDefault(nonSortedListUser => nonSortedListUser.value == sortedListUser))
.Where(x => x != null);
Hope it helps!
Upvotes: 1