Rohit Rohit - 19 days ago 5
C# Question

Conditional order by in linq

I have ViewModel as follows

public class LMS_ClassDiscussionListViewModel
{
public int ReplyCount { get; set; }
public LMS_ClassDiscussion ClassDiscussion { get; set; }
}


and the model LMS_ClassDiscussion which is referred in above view model is as follows

public partial class LMS_ClassDiscussion
{
[Key]
public int ClassDiscussionID { get; set; }
public int? ParentClassDiscussionID { get; set; }
public int MessageTypeID { get; set; }
public int ClassID { get; set; }
public int DiscussionUserID { get; set; }
public int NotificationStatusID { get; set; }
public string Discussion { get; set; }
public DateTime DiscussionDate { get; set; }
public bool IsPrivate { get; set; }
public bool IsRead { get; set; }
public string DiscussionTitle { get; set; }
}


I am getting the records in list as follows

List<LMS_ClassDiscussionListViewModel> modelList = GetData();


So, this list I want to sort based on
NotificationStatusID = 2
.

Means, those records which has
NotificationStatusID
as 2 it should come first and rest after that.

So, for this I have tried in below way but the list is not getting sorted

modelList = modelList.OrderBy(x => x.ClassDiscussion.NotificationStatusID)
.ThenBy(x => x.ClassDiscussion.NotificationStatusID == 2)
.ToList();


How can i sort this list with
NotificationStatusID = 2
?

Thanks !

Answer

You may first select your elements with Id = 2 and then concatenate the rest at the end using Enumerable.Concat:

var result = modelList.Where(x => x.ClassDiscussion.NotificationStatusID == 2)
        .Concat(modeList.Where(x => x.ClassDiscussion.NotificationStatusID != 2));
Comments