Sorting in a DataGridView using the DataSource property

I have List

one which contains elements like:

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

      

List

tied to the DataGridView

following:

MyDataGridView.DataSource = MyList;

      

I want the element to https:\\localhost\

be on top. How can I achieve this?

+2


source to share


3 answers


You need to sort the list before linking it.

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

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

      



This is a very simple example. There is also a method OrderBy

for sorting in ascending order. If you have a list of objects, you must change the return type (i => i) to have a property, for example the date will look like.OrderByDescending<string, DateTime>(i => i.SomeDate)

+2


source


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

      

0


source


If, instead, you want to specifically put localhost at the beginning, but sort the rest in ascending order, you can instead do something like this:

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

      

Note that generic method types are usually inferred by the compiler.

0


source







All Articles