簡體   English   中英

使用自定義比較對ArrayList進行排序

[英]Sort ArrayList with custom comparison

我正在嘗試使用c#對ArrayList進行排序。 ArrayList包含可比較的對象時,可以使用list.Sort()進行排序,但我需要對包含不可比較對象的ArrayList進行排序。 例如,假設該對象是Ring ,並且具有屬性屬性Price 然后,我需要按價格順序對ArrayList進行排序。 如果可以選擇升序或降序,則將更有幫助。 謝謝!

大段引用

arrAtdMon = **(ArrayList)** hashTb [unixMon];

如果(arrAtdMon!= null)monCount = arrAtdMon.Count;

int [] arrayMax = {monCount,tueCount,wedCount,thuCount,friCount};

int maxValue = arrayMax.Max();

KidAttendance valMon = null; 字符串monTagName = string.Empty;

大段引用

上面的數組列表將對其進行自我排序。

您可以通過實現IComparer接口來做到這一點:

public class Ring : IComparer
{
    public decimal Price { get; set; }

    public int Compare(object x, object y)
    {
        return ((Ring)x).Price.CompareTo(((Ring)y).Price);
    }
}

工作小提琴

首先,您確實應該使用List<T>類,而不是ArrayList 這樣做不會解決您的問題,但是會使代碼更不易碎,更易於維護。

至於特定的問題,您想做這樣的事情……

假設:

class Ring { public decimal Price { get; set; } }

然后:

ArrayList list = ...; // Initialized as some collection of Ring instances

list.Sort(Comparer.Create((r1, r2) => r1.Price.CompareTo(r2.Price)));

這將使用(r1, r2) => r1.Price.CompareTo(r2.Price) Comparison<T>創建一個新的Comparer實例。 也就是說,對於要比較的每對對象,將第一個對象的價格與第二個對象的價格進行比較。

假設這些對象共享一個基類或帶有price屬性的接口,則您應該能夠執行以下操作:

// Base class with price property, could also be an shared interface
public abstract class Product
{
    public decimal Price{get;set;}
}

public class Ring : Product
{

}
public class Bag : Product
{

}

// Some test data
var myUnsortedArray = new Product[]{new Ring{Price = 1.2m}, new Bag{Price=2.5m}};

// Easy sort with LINQ
var sortedProducts = myUnsortedArray.OrderBy(p => p.Price).ToArray();
var sortedProductsDescending = myUnsortedArray.OrderByDescending(p => p.Price).ToArray();

UPDATE

我剛剛意識到問題是關於ArrayLists的,下面是更改的解決方案:

// Some test data
var myUnsortedArrayList = new ArrayList{new Ring{Price = 1.2m}, new Bag{Price=2.5m}};

// Easy sort with LINQ
var sortedProducts = myUnsortedArrayList.OfType<Product>().OrderBy(p => p.Price).ToArray();
var sortedProductsDescending = myUnsortedArrayList.OfType<Product>().OrderByDescending(p => p.Price).ToArray();

要對一組對象進行排序,該對象必須是Comparable,並且可以在CompareTo()方法中設置所需的比較: IComparable信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM