Files
StockHistory/StockHistory/SmartListViewComparer.cs

64 lines
2.0 KiB
C#

using System.Collections;
using System.Runtime.InteropServices;
namespace StockHistory;
public class SmartListViewComparer : IComparer
{
private readonly int col;
private readonly SortOrder order;
public SmartListViewComparer(int column, SortOrder order)
{
col = column;
this.order = order;
}
public int Compare(object x, object y)
{
string a = ((ListViewItem)x).SubItems[col].Text;
string b = ((ListViewItem)y).SubItems[col].Text;
// Tomma värden sist
if (string.IsNullOrWhiteSpace(a) && string.IsNullOrWhiteSpace(b)) return 0;
if (string.IsNullOrWhiteSpace(a)) return order == SortOrder.Ascending ? 1 : -1;
if (string.IsNullOrWhiteSpace(b)) return order == SortOrder.Ascending ? -1 : 1;
int result = CompareSmart(a, b);
return order == SortOrder.Ascending ? result : -result;
}
private int CompareSmart(string a, string b)
{
// Procent
if (a.EndsWith("%") && b.EndsWith("%") &&
double.TryParse(a.TrimEnd('%'), out double pa) &&
double.TryParse(b.TrimEnd('%'), out double pb))
return pa.CompareTo(pb);
// Valuta
string ac = a.Replace("kr", "").Replace("$", "").Replace("€", "").Trim();
string bc = b.Replace("kr", "").Replace("$", "").Replace("€", "").Trim();
if (double.TryParse(ac, out double ca) && double.TryParse(bc, out double cb))
return ca.CompareTo(cb);
// Datum
if (DateTime.TryParse(a, out DateTime da) && DateTime.TryParse(b, out DateTime db))
return da.CompareTo(db);
// Tal
if (double.TryParse(a, out double na) && double.TryParse(b, out double nb))
return na.CompareTo(nb);
// Naturlig sortering
return StrCmpLogicalW(a, b);
}
[System.Runtime.InteropServices.DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
private static extern int StrCmpLogicalW(string x, string y);
}