2

I have a List that contains items, for example:

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\\

The List is bound to a DataGridView as follows:

MyDataGridView.DataSource = MyList;

I want the item https:\\localhost\ to be on the top. How can I achieve this?

3 Answers 3

2

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)

Sign up to request clarification or add additional context in comments.

Comments

0

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;
...

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.