-1

I am trying to implement custom sorting for a functionality that goes like the below: A list of users (First Middle Last name combination)where middle name is optional. Here are a few criterias that I have for sorting:

1-first,middle,last

2-first,last,middle

3-last,middle,first

4-last,first,middle

I tried using linq's orderby followed by then but it wont work that way coz as i get the list of users ,i am converting the list of users to IEnumerable & pass this to the view to bind it to dropdownlist. Here is my final list assigned to the viewmodal:

 viewModel.Users= users
                     .Select(usr=> new SelectListItem()
                     {
                         Text = $"{usr.FirstName} {usr.MiddleName} {usr.LastName}",
                         Value = $"{usr.FirstName} {usr.MiddleName} {usr.LastName}"
                     }).ToArray();

So the question is how do i sort IEnumerable items based on the above criteria?

I am aware that this wont work with the existing sorting & I need some help in custom sorting i.e. more of creating an extension method that will be able to sort based on the above critera. Any help is appreciated. Thanks.

Ms1
  • 45
  • 5

1 Answers1

2

As far as I understand your question You don't need custom sorting for that. You can easily sort IEnumerable like this.

1-first,middle,last

users.OrderBy(item => item.Firstname).ThenBy(item => item.Midname).ThenBy(item => item.Lastname);

2-first,last,middle

users.OrderBy(item => item.Firstname).ThenBy(item => item.Lastname).ThenBy(item => item.Midname);

3-last,middle,first

users.OrderBy(item => item.Lastname).ThenBy(item => item.Midname).ThenBy(item => item.Firstname);

4-last,first,middle

users.OrderBy(item => item.Lastname).ThenBy(item => item.Firstname).ThenBy(item => item.Midname);
MrMoeinM
  • 2,080
  • 1
  • 11
  • 16
  • 1
    I think the answer is mostly correct but I think that he want the user to be able to select the sorting, so I would add a switch or a if to allow this – Iria Jul 03 '21 at 08:47
  • Thanks for the quick response. As i mentioned it in the question, i did used order & then of linq to achieve this but there is a slight confusion that i have which might be silly but i have to ask it anyway. This sorting will persist if i convert it into selectitem lists? – Ms1 Jul 03 '21 at 09:44
  • 1
    @user15532895 IEnumerable/IEnumerable makes no guarantees about ordering. It depends on implementation behind that interface. Look at [this](https://stackoverflow.com/a/10409944/5964792). So I suggest you use List insted of IEnumerable. If you convert your IEnumerable to List you can also use Sort method with custom IComparer – MrMoeinM Jul 03 '21 at 09:55