Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Problem Sorting List
Message
From
15/06/2010 03:01:23
 
 
To
15/06/2010 02:07:13
General information
Forum:
ASP.NET
Category:
Coding, syntax and commands
Miscellaneous
Thread ID:
01468908
Message ID:
01468925
Views:
34
>>I have loaded a list with Windows Services:
>>
>>
>>public static List<ServiceController> GetAllServices()
>>{
>>    ServiceController[] Temp = ServiceController.GetServices();
>>    List<ServiceController> Services = new List<ServiceController>(Temp);
>>    Services.Sort();
>>
>>    return Services;
>>}
>>
>>
>>The Sort line throws the error "Failed to compare two elements in the array." Google hits are obscure on this. Anyone know what this is about?
>
>As Bonnie said, the class must implement IComparable, IComparable(T)
>
>A 4th possibility is to provide an IComparer(T) to the sort
>
>( I would prefer to sort the array temp and then adding it to the list, rather than sorting the list)
>
>
>	class Test1
>	{
>
>		static void Main()
>		{
>			var xx = GetAllServices();
>			foreach (var service in xx)
>				Console.WriteLine(service.DisplayName);
>			Console.ReadLine();
>		}
>		public static List<ServiceController> GetAllServices()
>		{
>			ServiceController[] temp = ServiceController.GetServices();
>			//Array.Sort(temp, new ServiceControllerComparer());
>			List<ServiceController> Services = new List<ServiceController>(temp);
>			Services.Sort(new ServiceControllerComparer());
>
>			return Services;
>		}
>	}
>
>
>	class ServiceControllerComparer : IComparer<ServiceController>
>	{
>
>		public int Compare(ServiceController x, ServiceController y)
>		{
>			if (x == null)
>				return y == null ? 0 : -1;
>
>			if (y == null)
>				return 1;
>
>			return x.DisplayName.CompareTo(y.DisplayName);
>		}
>	}
>
You were up early :-}
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform