2
\$\begingroup\$

I have a repository method which retrieve a list of items, for example:

StaffID: 250026965
Name: Abbasov Islam
FreeTextName: NULL

StaffID: NULL
Name: NULL
FreeTextName: Antonio Puccio

StaffID: 358
Name: Prosinecki Robert
FreeTextName: NULL

I have to sort this list in this manner:

First the items with StaffID > 0 by Name, then the items with StaffID == NULL by FreeTextName.

In the example case:

StaffID: 250026965
Name: Abbasov Islam
FreeTextName: NULL

StaffID: 358
Name: Prosinecki Robert
FreeTextName: NULL

StaffID: NULL
Name: NULL
FreeTextName: Antonio Puccio

At the moment I am doing:

var resList = conn.Query<TeamSheetStaffPoco>("[dbo].[TList]", p, commandType: CommandType.StoredProcedure).AsList();
var result = resList.Where(x => x.StaffID> 0).OrderBy(y => y.Name).ToList();
result.AddRange(resList.Where(x => x.StaffID== null).OrderBy(y => y.FreeTextName).ToList());

It works, but I am not sure if exist a more concise and elegant mode to to do the same thing.

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

Use a custom IComparer<T> to sort the the items.

class TeamSheetStaffPocoComparer : IComparer<TeamSheetStaffPoco> {

    public int Compare(TeamSheetStaffPoco a, TeamSheetStaffPoco b) {

        if (a.StaffID == null && b.StaffId == null)
        {
            return a.FreeTextName.CompareTo(b.FreeTextName);
        }

        if (a.StaffID > 0 && b.StaffID > 0) 
        {
            return a.Name.CompareTo(b.Name);
        }

        return a.StaffID > 0 ? 1 : -1;
    }

 }

Then you can simplify the last two lines to

var result = resList.OrderBy(x => x, new TeamSheetStaffPocoComparer()).ToList();

Also, you can now reuse the comparison class elsewhere too if you wish.

\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.