Mehrdad Ghaffari Mehrdad Ghaffari - 3 months ago 14
C# Question

sort object using custom sorter doesn't work

I have this custom sorter:

public class AlphaNumericSorter : IComparer<string>
{
public int Compare(string x, string y)
{
return SafeNativeMethods.StrCmpLogicalW(x, y);
}
}

[SuppressUnmanagedCodeSecurity]
internal static class SafeNativeMethods
{
[DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
public static extern int StrCmpLogicalW(string psz1, string psz2);
}


I want to sort my all objects but it just sort one of my column and i have to pass my column.
I need to sort this type of list based on
jointnumber


List<ViewTestPackageHistorySheet> testList = _reportTestPackageHistorySheetRepository.ShowReport(Id).ToList();

testList.Sort(new AlphaNumericSorter());


I got this error :

'System.Collections.Generic.IComparer<ViewDomainClass.Report.TestPackage.ViewTestPackageHistorySheet>'


But this works :

List<string> testList = _reportTestPackageHistorySheetRepository.ShowReport(Id).Select(i=>i.JointNumber).ToList();
testList.Sort(new AlphaNumericSorter());

Answer

You might want to implement is like: IComparer<ViewTestPackageHistorySheet>

You want to compare ViewTestPackageHistorySheet instead of string

Something like:

public class AlphaNumericSorter : IComparer<ViewTestPackageHistorySheet>
{
    public int Compare(ViewTestPackageHistorySheet x, ViewTestPackageHistorySheet y)
    {
        return SafeNativeMethods.StrCmpLogicalW(x.JointNumber, y.JointNumber);
    }
}

[SuppressUnmanagedCodeSecurity]
internal static class SafeNativeMethods
{
    [DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
    public static extern int StrCmpLogicalW(string psz1, string psz2);
}

Use it like:

var result = _reportTestPackageHistorySheetRepository.ShowReport(Id).ToList();

result.Sort(new AlphaNumericSorter());