Skip to main content
All docs
V25.1
  • Row

    Worksheet.Sort(CellRange, IEnumerable<SortFieldBase>) Method

    Sorts the specified range by multiple columns.

    Namespace: DevExpress.Spreadsheet

    Assembly: DevExpress.Spreadsheet.v25.1.Core.dll

    NuGet Package: DevExpress.Spreadsheet.Core

    Declaration

    void Sort(
        CellRange range,
        IEnumerable<SortFieldBase> sortFields
    )

    Parameters

    Name Type Description
    range CellRange

    The range of cells in a worksheet.

    sortFields IEnumerable<SortFieldBase>

    A list of SortFieldBase objects which specify the columns by which to sort.

    Remarks

    To sort by multiple columns, perform the following steps.

    • Create the SortFieldBase object for each of the columns from which to sort. Specify the position of this column within the range using the SortFieldBase.ColumnOffset property and assign a comparer using the SortField.Comparer property. Instead of implementing your comparer with the IComparer<T><CellValue,> interface, you can use one of the built-in comparers that are responsible for sort operations performed by users. There are two built-in comparers: Worksheet.Comparers.Ascending used for sorting in ascending order, and Worksheet.Comparers.Descending used for sorting in descending order.
    • Create a list containing sort fields.
    • Use the Worksheet.Sort method with two parameters: the CellRange to sort, and the list of sort fields.

    Sort_MultipleColumns

    View Example

    workbook.LoadDocument("Documents\\Sortsample.xlsx");
    Worksheet worksheet = workbook.Worksheets[0];
    
    // Create sorting fields.
    List<SortFieldBase> fields = new List<SortFieldBase>();
    
    // First sorting field. First column (offset = 0) will be sorted using ascending order.
    SortField sortField1 = new SortField();
    sortField1.ColumnOffset = 0;
    sortField1.Comparer = worksheet.Comparers.Ascending;
    fields.Add(sortField1);
    
    // Second sorting field. Second column (offset = 1) will be sorted using ascending order.
    SortField sortField2 = new SortField();
    sortField2.ColumnOffset = 1;
    sortField2.Comparer = worksheet.Comparers.Ascending;
    fields.Add(sortField2);
    
    // Sort the range by sorting fields.
    CellRange range = worksheet.Range["A3:F22"];
    worksheet.Sort(range, fields);
    

    The following code snippets (auto-collected from DevExpress Examples) contain references to the Sort(CellRange, IEnumerable<SortFieldBase>) method.

    Note

    The algorithm used to collect these code examples remains a work in progress. Accordingly, the links and snippets below may produce inaccurate results. If you encounter an issue with code examples below, please use the feedback form on this page to report the issue.

    See Also