在linq c中从db中选择数据后,如何通过id获取排序输出#

时间:2016-11-16 07:20:39

标签: c# linq sorting linq-to-entities

我有一个integers ids列表,从表格中我只需要为列表中的ID I have already done 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();

现在,当我运行此查询时,我从db获取了详细信息列表,但它位于sorted form but i need to sort them by the form which they were中的list (SelectedUser).

1 个答案:

答案 0 :(得分:1)

它不是太漂亮,但您可以使用第一个列表,然后使用FirstOrDefault从第二个列表中进行选择。

如果在Where列表中找不到第一个SelectedUser,则最后objValidateUserList确保您不包含空值。

var sortedList = SelectedUser.Select(
        sortedListUser => objValidateUserList.FirstOrDefault(nonSortedListUser => nonSortedListUser.value == sortedListUser))
        .Where(x => x != null);

希望它有所帮助!