How to make sorting by two columns in datagridview? The data source is a txt file. Only 5 columns of them need to sort by two.

For example: А0, А450, Y56200, Y9600 and so on.

The data itself is presented in the form of string values.
I understand how it is possible to make sorting on one column, but on two mind I will not put. Tell me please.

  • Describe the 5-field class and initialize it. The resulting collection can be sorted using LINQ to Object, using the methods OrderBy, OrderByDescemding, ThenBy and ThenByDescending - Vadim Prokopchuk
  • Write what is stored in the file and by what fields you need to sort. I will write the code - Vadim Prokopchuk
  • X56820 Y47283 W84742 H373 A450; sorting should be carried out on the fields Y and A. - Jeron
  • one

1 answer 1

Suppose you have a model that describes the structure of a single record in a file:

  class Example { public string X { get; set; } public string Y { get; set; } public string W { get; set; } public string H { get; set; } public string A { get; set; } } 

And the file has already been read and written to the collection, for example

 IEnumerable<Example> exampleCollection 

Then you can sort the collection using LINQ to Object:

  1. OrderBy - sorts the elements of a sequence in ascending order
  2. OrderByDescending - sorts the elements of a sequence in descending order
  3. ThenBy - performs additional ordering of sequence elements in ascending order.
  4. ThenByDescending - performs additional ordering of sequence elements in descending order.

In your case, to sort by two columns, use:

 exampleCollection = exampleCollection.OrderBy(e => eY).ThenBy(e => eA); 

Attention! This query uses deferred execution.

What does this code do?

This code sorts the collection in ascending order by the Y field; if the Y fields are equal, then additional sorting is performed in the A field, as well as in ascending order.

  • Thank! Exactly what is needed! - Jeron
  • Hmm, I have a question. Can I describe the structure of the record in datagridview? - Jeron
  • @Jeron; I don't work with Window Forms, so I can't say anything specifically. Most likely, the structure of the record in the DataGridView is represented by the collection - Vadim Prokopchuk