これは必ずしも元の質問に答えているわけではありませんが、概説したいくつかの可能性をいくらか拡張します。他の人が同様の問題に遭遇した場合に備えて、これを投稿しています。ここに投稿されたソリューションは、他の場合に役立つ可能性があるオプションによる一般的な順序の概要を示しています。この例では、ファイル リストをさまざまなプロパティで並べ替えます。
/// <summary>
/// Used to create custom comparers on the fly
/// </summary>
/// <typeparam name="T"></typeparam>
public class GenericCompare<T> : IComparer<T>
{
// Function use to perform the compare
private Func<T, T, int> ComparerFunction { set; get; }
// Constructor
public GenericCompare(Func<T, T, int> comparerFunction)
{
ComparerFunction = comparerFunction;
}
// Execute the compare
public int Compare(T x, T y)
{
if (x == null || y == null)
{
// These 3 are bell and whistles to handle cases where one of the two is null, to sort to top or bottom respectivly
if (y == null && x == null) { return 0; }
if (y == null) { return 1; }
if (x == null) { return -1; }
}
try
{
// Do the actual compare
return ComparerFunction(x, y);
}
catch (Exception ex)
{
// But muffle any errors
System.Diagnostics.Debug.WriteLine(ex);
}
// Oh crud, we shouldn't be here, but just in case we got an exception.
return 0;
}
}
実装では…</p>
GenericCompare<FileInfo> DefaultComparer;
if (SortOrder == SORT_FOLDER_FILE)
{
DefaultComparer = new GenericCompare<FileInfo>((fr1, fr2) =>
{
return fr1.FullName.ToLower().CompareTo(fr2.FullName.ToLower());
});
}
else if (SortOrder == SORT_SIZE_ASC)
{
DefaultComparer = new GenericCompare<FileInfo>((fr1, fr2) =>
{
return fr1.Length.CompareTo(fr2.Length);
});
}
else if (SortOrder == SORT_SIZE_DESC)
{
DefaultComparer = new GenericCompare<FileInfo>((fr1, fr2) =>
{
return fr2.Length.CompareTo(fr1.Length);
});
}
else
{
DefaultComparer = new GenericCompare<FileInfo>((fr1, fr2) =>
{
return fr1.Name.ToLower().CompareTo(fr2.Name.ToLower());
});
}
var ordered_results = (new DirectoryInfo(@"C:\Temp"))
.GetFiles()
.OrderBy(fi => fi, DefaultComparer);
大きな利点は、注文ごとに新しいクラスを作成する必要がなく、新しいラムダを接続するだけでよいことです。明らかに、これはあらゆる種類の方法で拡張できるため、いつかどこかで誰かに役立つことを願っています.