我有一些问题重构和订购一份清单。
我有一个名为DomainCollection的类,它继承自KeyedCollection。
public class DomainCollection<T> : KeyedCollection<ID, T>, IDomainCollection<T> where T : class, IDomainObject我创建并填写了一个名为“订单”的列表。
var orders = new DomainCollection<Order>();订单包含一个OrderType,它包含自己的OrderTypes。因此,如果我们有一个条件,我们可以执行一些操作,它将如下所示
if(order.Type.Type.Equals(OrderTypes.InvestmentToBankY))
{
//Currently: logic where it creates a new list and adds the list to the existing order
//list and the very end.
}我的问题。我希望能够对我的订单列表进行排序,这样我使用InvestmentToBankY的订单就可以位于DomainCollection的底部或顶部。
发布于 2022-10-05 13:54:43
如果您只想遍历顶部有InvestmentToBankY命令的元素,只需使用以下内容:
// Add .ToList() if you want to materialize the items immediately.
var orderedOrders =
orders.OrderBy(o => o.Type.Type.Equals(OrderTypes.InvestmentToBankY));
foreach (var order in orderedOrders)
{
// This will follow the desired order.
}如果您想最终得到一个排序的DomainCollection,那么一个不那么有效的方法就是使用新的顺序重构DomainCollection。下面这样的东西应该能起作用:
public class DomainCollection<T> : KeyedCollection<ID, T>, IDomainCollection<T>
where T : class, IDomainObject
{
public DomainCollection() { }
public DomainCollection(IEnumerable<T> items)
{
foreach (var item in items)
this.Add(item);
}
protected override ID GetKeyForItem(T item)
{
// TODO: implement GetKeyForItem.
throw new NotImplementedException();
}
}然后,您可以使用它如下:
var orderedOrders =
orders.OrderBy(o => o.Type.Type.Equals(OrderTypes.InvestmentToBankY));
orders = new DomainCollection(orderedOrders);避免创建新集合的更好的解决方案是依赖以下事实:KeyedCollection继承Collection<T>的Items属性为 a List<T>,并编写自己的排序方法,使用Comparison<T>或IComparer<T>调用相应的List<T>.Sort重载。下面是后者的一个例子:
public class DomainCollection<T> : KeyedCollection<ID, T>, IDomainCollection<T>
where T : class, IDomainObject
{
protected override ID GetKeyForItem(T item)
{
// TODO: implement GetKeyForItem.
throw new NotImplementedException();
}
public void Sort(IComparer<T> comparer)
{
((List<T>)this.Items).Sort(comparer);
}
}
public class OrderComparer : IComparer<Order>
{
public int Compare(Order x, Order y)
{
return x.Type.Type.Equals(OrderTypes.InvestmentToBankY).
CompareTo(y.Type.Type.Equals(OrderTypes.InvestmentToBankY));
}
}用法:
orders.Sort(new OrderComparer());https://stackoverflow.com/questions/73961087
复制相似问题