In your SortByColumn method, toggle the sort direction and resort the data based on the new column. For example:
csharp
private void SortByColumn(string column)
{
if (column == SortColumn)
{
SortAscending = !SortAscending;
}
else
{
SortColumn = column;
SortAscending = true;
}
// Sort the data based on the new column and direction
Data = Data.OrderBy(x => x.GetType().GetProperty(SortColumn)!.GetValue(x)!).ToList();
if (!SortAscending)
{
Data = Data.Reverse().ToList();
}
}
Note that this example uses reflection to sort the data, which may not be the most efficient approach for large datasets. For better performance, you can implement custom IComparer classes for each column or use a library that provides sorting functionality for Blazor.
Bind your table data to the sorted list in your component's markup.
Here's an example of what the complete Blazor Server component might look like:
csharp
@page "/table"
@using System.Linq.Expressions
@using System.Reflection
<table>
<thead>
<tr>
<th @onclick="() => SortByColumn("Name")">Name</th>
<th @onclick="() => SortByColumn("Age")">Age</th>
<th @onclick="() => SortByColumn("City")">City</th>
</tr>
</thead>
<tbody>
@foreach (var dataItem in Data)
{
<tr>
<td>@dataItem.Name</td>
<td>@dataItem.Age</td>
<td>@dataItem.City</td>
</tr>
}
</tbody>
</table>
@code {
private List<DataItem> Data { get; set; }
public string SortColumn { get; set; } = "Name";
public bool SortAscending { get; set; } = true;
protected override async Task OnInitializedAsync()
{
// Retrieve data for the table
Data = new List<DataItem>
{
new DataItem { Name = "John", Age = 30, City = "New York" },
new DataItem { Name = "Jane", Age = 25, City = "Los Angeles" },
new DataItem { Name = "Bob", Age = 35, City = "Chicago" }
};
// Sort the data based on the initial sorting property values
Data = Data.OrderBy(x => x.GetType().GetProperty(SortColumn)!.GetValue(x)!).ToList();
if (!SortAscending)
{
Data = Data.Reverse().ToList();
}
}
private void SortByColumn(string column)
{
if (column == SortColumn)
{
SortAscending = !SortAscending;
}
else
{
SortColumn = column;
SortAscending = true;
}
// Sort the data based on the new column and direction
Data = Data.OrderBy(x => x.GetType().GetProperty(SortColumn)!.GetValue(x)!).ToList();
if (!SortAscending)
{
Data = Data.Reverse().ToList();
}
}
public class DataItem
{
public string Name { get; set; }
public int Age { get; set; }
public string City { get; set; }
}
}