You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Connected.Components/Utilities/SortingAssistent.cs

47 lines
1.1 KiB

// Copyright (c) MudBlazor 2021
// MudBlazor licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Linq.Expressions;
using System.Reflection;
using Connected.Components;
namespace Connected.Utilities;
public static class SortingAssistent
{
public static void UpdateOrder<T>(this IEnumerable<T> items, ItemDropInfo<T> dropInfo, Expression<Func<T, int>> valueUpdater, int zoneOffset = 0)
{
var memberSelectorExpression = valueUpdater.Body as MemberExpression;
if (memberSelectorExpression == null) { throw new InvalidOperationException(); }
var property = memberSelectorExpression.Member as PropertyInfo;
if (property == null) { throw new InvalidOperationException(); }
var newIndex = dropInfo.IndexInZone + zoneOffset;
var item = dropInfo.Item;
int index = 0;
foreach (var _item in items.OrderBy(x => (int)property.GetValue(x)))
{
if (_item.Equals(item) == true)
{
property.SetValue(item, newIndex);
}
else
{
if (index == newIndex)
{
index++;
}
property.SetValue(_item, index);
index++;
}
}
}
}