views:

458

answers:

3

I have a List that contain items for eg:

1)https:\10.12.23\ 2)https:\12.23.12.25\ 3)https:\localhost\ 4)https:\12.25.12.2\ 5)https:\12.36.12.22\ 6)https:\12.88.12.32\

When I bound List into DataGridView as below:

MyDataGridView.DataSource = MyList;

I want that the item "https:\localhost\" should be on the top.. how can I acheive this??

Pleas help!!

+2  A: 

You need to sort the list before binding it.

List<string> items = new List<string>();

List<string> sortedItems = items
    .OrderByDescending<string, string>(i => i)
    .ToList<string>();

This is a very basic example. There is also an OrderBy method to sort ascending. If you had an object list, you would change the return type of the (i => i) to have the property for example date would look like .OrderByDescending<string, DateTime>(i => i.SomeDate)

David Basarab
A: 

If you just want to keep https://localhost/ at the top, then:


int i = items.FindIndex(delegate(string s) { return s.Contains("localhost"); });
if (i > -1) {
  string localhost = items[i];
  items.RemoveAt(i);
  items.Insert(0, localhost);
}
MyDataGridView.DataSource = items;
...
Tadas
A: 

If instead you wanted to specifically float localhost to the top, but sort the rest ascending, you could instead do something like this:

MyDataGridView.DataSource = MyList
    .OrderByDescending(i => i.Contains("://localhost/", StringComparison.OrdinalIgnoreCase))
    .ThenBy(i => i)
    .ToList();

Note that the generic types on the methods can usually be inferred by the compiler.

dahlbyk