@DavidMills द्वारा स्वीकार कर लिया जवाब है काफी अच्छा है, लेकिन मुझे लगता है कि इसे बेहतर किया जा सकता है। एक के लिए, ComparisonComparer<T>
कक्षा को परिभाषित करने की आवश्यकता नहीं है जब ढांचे में पहले से ही एक स्थिर विधि Comparer<T>.Create(Comparison<T>)
शामिल है। इस विधि का उपयोग फ्लाई पर IComparison
बनाने के लिए किया जा सकता है।
इसके अलावा, यह IList<T>
से IList
पर खतरनाक होने की संभावना है। अधिकांश मामलों में मैंने देखा है, List<T>
जो IList
लागू करता है IList<T>
को लागू करने के लिए दृश्यों के पीछे उपयोग किया जाता है, लेकिन इसकी गारंटी नहीं है और भंगुर कोड का कारण बन सकता है।
आखिरकार, अधिभारित List<T>.Sort()
विधि में 4 हस्ताक्षर हैं और उनमें से केवल 2 लागू किए गए हैं।
public static class IListExtensions
{
public static void Sort<T>(this IList<T> list)
{
if (list is List<T>)
{
((List<T>)list).Sort();
}
else
{
List<T> copy = new List<T>(list);
copy.Sort();
Copy(copy, 0, list, 0, list.Count);
}
}
public static void Sort<T>(this IList<T> list, Comparison<T> comparison)
{
if (list is List<T>)
{
((List<T>)list).Sort(comparison);
}
else
{
List<T> copy = new List<T>(list);
copy.Sort(comparison);
Copy(copy, 0, list, 0, list.Count);
}
}
public static void Sort<T>(this IList<T> list, IComparer<T> comparer)
{
if (list is List<T>)
{
((List<T>)list).Sort(comparer);
}
else
{
List<T> copy = new List<T>(list);
copy.Sort(comparer);
Copy(copy, 0, list, 0, list.Count);
}
}
public static void Sort<T>(this IList<T> list, int index, int count,
IComparer<T> comparer)
{
if (list is List<T>)
{
((List<T>)list).Sort(index, count, comparer);
}
else
{
List<T> range = new List<T>(count);
for (int i = 0; i < count; i++)
{
range.Add(list[index + i]);
}
range.Sort(comparer);
Copy(range, 0, list, index, count);
}
}
private static void Copy(IList<T> sourceList, int sourceIndex,
IList<T> destinationList, int destinationIndex, int count)
{
for (int i = 0; i < count; i++)
{
destinationList[destinationIndex + i] = sourceList[sourceIndex + i];
}
}
}
:
List<T>.Sort()
List<T>.Sort(Comparison<T>)
List<T>.Sort(IComparer<T>)
List<T>.Sort(Int32, Int32, IComparer<T>)
नीचे वर्ग IList<T>
इंटरफेस के लिए सभी 4 List<T>.Sort()
हस्ताक्षर लागू करता है
उपयोग:
class Foo
{
public int Bar;
public Foo(int bar) { this.Bar = bar; }
}
void TestSort()
{
IList<int> ints = new List<int>() { 1, 4, 5, 3, 2 };
IList<Foo> foos = new List<Foo>()
{
new Foo(1),
new Foo(4),
new Foo(5),
new Foo(3),
new Foo(2),
};
ints.Sort();
foos.Sort((x, y) => Comparer<int>.Default.Compare(x.Bar, y.Bar));
}
विचार यहाँ अंतर्निहित List<T>
की कार्यक्षमता का लाभ उठाने के लिए जब भी संभव छँटाई को संभालने के लिए है। दोबारा, अधिकांश IList<T>
कार्यान्वयन जो मैंने देखा है इसका उपयोग करते हैं। उस स्थिति में जब अंतर्निहित संग्रह एक अलग प्रकार है, इनपुट सूची के तत्वों के साथ List<T>
का नया उदाहरण बनाने के लिए फ़ॉलबैक, सॉर्टिंग करने के लिए इसका उपयोग करें, फिर परिणामों को वापस इनपुट सूची में कॉपी करें। यह तब भी काम करेगा जब इनपुट सूची IList
इंटरफ़ेस को लागू नहीं करती है।
आप पहली जगह में आईएलिस्ट क्यों वापस लौटेंगे? डब्ल्यूसीएफ सेवा से? – DaeMoohn