המחלקה הסטטית – Utils

public static class Utils

    {

        private static bool sortDirection = true;

        /// <summary>

        /// This function sort the datagridview , first parameter is the
Datagridview name,

        /// second parameter is the dgv Datasource list

        /// </summary>

        /// <typeparam name="T"></typeparam>

        /// <param name="dgv"></param>

        /// <param name="lst"></param>

        /// <param name="e"></param>

        /// <returns></returns>

        public static
List<T> sortDGV<
T>(DataGridView
dgv, List<T> lst, DataGridViewCellMouseEventArgs e)

        {

            var dataGrid = (DataGridView)dgv;

            var colName = dataGrid.Columns[e.ColumnIndex].DataPropertyName;

            lst =
((IEnumerable)dataGrid.DataSource).Cast<T>().ToList();

 

            sortDirection = !sortDirection;

            if (sortDirection)

            {

                lst = lst.OrderBy(item =>
item.GetType().GetProperty(colName)?.GetValue(item,
null)).ToList();

            }

            else

            {

                lst =
lst.OrderByDescending(item =>
item.GetType().GetProperty(colName)?.GetValue(item,
null)).ToList();

            }

 

            dataGrid.DataSource = lst;

            return lst;

        }

    }