我在重構和排序串列時遇到了一些問題。
我有一個名為的類DomainCollection
,它繼承自KeyedCollection
.
public class DomainCollection<T> : KeyedCollection<ID, T>, IDomainCollection<T> where T : class, IDomainObject
我創建并填寫了一個名為訂單的串列。
var orders = new DomainCollection<Order>();
一個訂單包含一個包含其自己的 OrderTypes 的 OrderType。因此,如果我們有一個可以執行某些操作的條件,它看起來像這樣
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 的底部或頂部。
uj5u.com熱心網友回復:
如果您只想遍歷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.
}
如果你想得到一個 sorted 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的事實,并撰寫我們自己的排序方法,該方法使用 a或 an并呼叫相應的多載。這是后者的一個例子: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://www.uj5u.com/yidong/515630.html
標籤:C#。网林克键控集合