यह आवश्यक रूप से मूल प्रश्न का उत्तर नहीं दे रहा है, लेकिन यह कुछ हद तक उल्लिखित संभावनाओं को बढ़ाता है। अगर मैं इसी तरह की समस्या में आ जाता हूं तो मैं इसे पोस्ट कर रहा हूं। यहां पोस्ट किया गया समाधान विकल्प द्वारा एक सामान्य आदेश की रूपरेखा देता है जो अन्य मामलों में उपयोगी हो सकता है। इस उदाहरण में, मैं विभिन्न गुणों से एक फ़ाइल सूची सॉर्ट करना चाहता था।
/// <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;
}
}
कार्यान्वयन में
फिर ...
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);
बड़ा लाभ यह है कि आप तो मामले से प्रत्येक आदेश के लिए एक नया वर्ग बनाने की जरूरत नहीं है, आप बस एक नई लैम्ब्डा ऊपर तार कर सकते हैं। जाहिर है, इसे सभी प्रकार के तरीकों से बढ़ाया जा सकता है, इसलिए उम्मीद है कि यह कभी-कभी किसी, कहीं, किसी की मदद करेगा।
स्रोत
2013-09-01 05:32:44
गुणवत्ता linq लिंक! यद्यपि विधि आधारित सिंटैक्स में ऑर्डर-सिंटैक्स के बारे में बयान वास्तव में उत्तर का हिस्सा नहीं माना जाता था। :) –
@SteveKonves मैंने इसे अभी भी शामिल किया है। आप आसानी से अनदेखा कर सकते हैं;) –