KeyedCollection<TKey,TItem> 類別

定義

為內嵌在值之索引鍵的集合,提供抽象基底類別。

generic <typename TKey, typename TItem>
public ref class KeyedCollection abstract : System::Collections::ObjectModel::Collection<TItem>
public abstract class KeyedCollection<TKey,TItem> : System.Collections.ObjectModel.Collection<TItem>
[System.Runtime.InteropServices.ComVisible(false)]
[System.Serializable]
public abstract class KeyedCollection<TKey,TItem> : System.Collections.ObjectModel.Collection<TItem>
type KeyedCollection<'Key, 'Item> = class
    inherit Collection<'Item>
[<System.Runtime.InteropServices.ComVisible(false)>]
[<System.Serializable>]
type KeyedCollection<'Key, 'Item> = class
    inherit Collection<'Item>
Public MustInherit Class KeyedCollection(Of TKey, TItem)
Inherits Collection(Of TItem)

類型參數

TKey

集合中的索引鍵類型。

TItem

集合中項目的類型。

繼承
Collection<TItem>
KeyedCollection<TKey,TItem>
衍生
屬性

範例

本節包含兩個程式碼範例。 第一個範例示範衍生自 KeyedCollection<TKey,TItem> 所需的最低程式碼,並示範許多繼承的方法。 第二個範例示範如何覆寫 的 KeyedCollection<TKey,TItem> 受保護方法來提供自訂行為。

範例 1

此程式碼範例示範從 KeyedCollection<TKey,TItem> 衍生集合類別所需的最小程式代碼:覆 GetKeyForItem 寫 方法,並提供委派給基類建構函式的公用建構函式。 程式碼範例也會示範繼承自 KeyedCollection<TKey,TItem> 和 類別的許多屬性和 Collection<T> 方法。

類別 SimpleOrder 是一個非常簡單的要求清單,其中包含 OrderItem 物件,每個物件都以順序表示明細專案。 的 OrderItem 索引鍵是不可變的,這是衍生自 KeyedCollection<TKey,TItem> 的類別的重要考慮。 如需使用可變動索引鍵的程式碼範例,請參閱 ChangeItemKey

using namespace System;
using namespace System::Collections::Generic;
using namespace System::Collections::ObjectModel;

// This class represents a simple line item in an order. All the 
// values are immutable except quantity.
// 
public ref class OrderItem
{
private:
    int _quantity;
    
public:
    initonly int PartNumber;
    initonly String^ Description;
    initonly double UnitPrice;
    
    OrderItem(int partNumber, String^ description, 
        int quantity, double unitPrice)
    {
        this->PartNumber = partNumber;
        this->Description = description;
        this->Quantity = quantity;
        this->UnitPrice = unitPrice;
    } 
    
    property int Quantity    
    {
        int get() { return _quantity; }
        void set(int value)
        {
            if (value < 0)
                throw gcnew ArgumentException("Quantity cannot be negative.");
            
            _quantity = value;
        }
    }
        
    virtual String^ ToString() override 
    {
        return String::Format(
            "{0,9} {1,6} {2,-12} at {3,8:#,###.00} = {4,10:###,###.00}", 
            PartNumber, _quantity, Description, UnitPrice, 
            UnitPrice * _quantity);
    }
};

// This class represents a very simple keyed list of OrderItems,
// inheriting most of its behavior from the KeyedCollection and 
// Collection classes. The immediate base class is the constructed
// type KeyedCollection<int, OrderItem>. When you inherit
// from KeyedCollection, the second generic type argument is the 
// type that you want to store in the collection -- in this case
// OrderItem. The first type argument is the type that you want
// to use as a key. Its values must be calculated from OrderItem; 
// in this case it is the int field PartNumber, so SimpleOrder
// inherits KeyedCollection<int, OrderItem>.
//
public ref class SimpleOrder : KeyedCollection<int, OrderItem^>
{
    // The parameterless constructor of the base class creates a 
    // KeyedCollection with an internal dictionary. For this code 
    // example, no other constructors are exposed.
    //
public:
    SimpleOrder() {}
    
    // This is the only method that absolutely must be overridden,
    // because without it the KeyedCollection cannot extract the
    // keys from the items. The input parameter type is the 
    // second generic type argument, in this case OrderItem, and 
    // the return value type is the first generic type argument,
    // in this case int.
    //
protected:
    virtual int GetKeyForItem(OrderItem^ item) override 
    {
        // In this example, the key is the part number.
        return item->PartNumber;
    }
};

public ref class Demo
{    
public:
    static void Main()
    {
        SimpleOrder^ weekly = gcnew SimpleOrder();

        // The Add method, inherited from Collection, takes OrderItem.
        //
        weekly->Add(gcnew OrderItem(110072674, "Widget", 400, 45.17));
        weekly->Add(gcnew OrderItem(110072675, "Sprocket", 27, 5.3));
        weekly->Add(gcnew OrderItem(101030411, "Motor", 10, 237.5));
        weekly->Add(gcnew OrderItem(110072684, "Gear", 175, 5.17));
        
        Display(weekly);
    
        // The Contains method of KeyedCollection takes the key, 
        // type, in this case int.
        //
        Console::WriteLine("\nContains(101030411): {0}", 
            weekly->Contains(101030411));

        // The default Item property of KeyedCollection takes a key.
        //
        Console::WriteLine("\nweekly(101030411)->Description: {0}", 
            weekly[101030411]->Description);

        // The Remove method of KeyedCollection takes a key.
        //
        Console::WriteLine("\nRemove(101030411)");
        weekly->Remove(101030411);
        Display(weekly);

        // The Insert method, inherited from Collection, takes an 
        // index and an OrderItem.
        //
        Console::WriteLine("\nInsert(2, New OrderItem(...))");
        weekly->Insert(2, gcnew OrderItem(111033401, "Nut", 10, .5));
        Display(weekly);

        // The default Item property is overloaded. One overload comes
        // from KeyedCollection<int, OrderItem>; that overload
        // is read-only, and takes Integer because it retrieves by key. 
        // The other overload comes from Collection<OrderItem>, the 
        // base class of KeyedCollection<int, OrderItem>; it 
        // retrieves by index, so it also takes an Integer. The compiler
        // uses the most-derived overload, from KeyedCollection, so the
        // only way to access SimpleOrder by index is to cast it to
        // Collection<OrderItem>. Otherwise the index is interpreted
        // as a key, and KeyNotFoundException is thrown.
        //
        Collection<OrderItem^>^ coweekly = weekly;
        Console::WriteLine("\ncoweekly[2].Description: {0}", 
            coweekly[2]->Description);
 
        Console::WriteLine("\ncoweekly[2] = gcnew OrderItem(...)");
        coweekly[2] = gcnew OrderItem(127700026, "Crank", 27, 5.98);

        OrderItem^ temp = coweekly[2];

        // The IndexOf method inherited from Collection<OrderItem> 
        // takes an OrderItem instead of a key
        // 
        Console::WriteLine("\nIndexOf(temp): {0}", weekly->IndexOf(temp));

        // The inherited Remove method also takes an OrderItem.
        //
        Console::WriteLine("\nRemove(temp)");
        weekly->Remove(temp);
        Display(weekly);

        Console::WriteLine("\nRemoveAt(0)");
        weekly->RemoveAt(0);
        Display(weekly);

    }
    
private:
    static void Display(SimpleOrder^ order)
    {
        Console::WriteLine();
        for each( OrderItem^ item in order )
        {
            Console::WriteLine(item);
        }
    }
};

void main()
{
    Demo::Main();
}

/* This code example produces the following output:

110072674    400 Widget       at    45.17 =  18,068.00
110072675     27 Sprocket     at     5.30 =     143.10
101030411     10 Motor        at   237.50 =   2,375.00
110072684    175 Gear         at     5.17 =     904.75

Contains(101030411): True

weekly(101030411)->Description: Motor

Remove(101030411)

110072674    400 Widget       at    45.17 =  18,068.00
110072675     27 Sprocket     at     5.30 =     143.10
110072684    175 Gear         at     5.17 =     904.75

Insert(2, New OrderItem(...))

110072674    400 Widget       at    45.17 =  18,068.00
110072675     27 Sprocket     at     5.30 =     143.10
111033401     10 Nut          at      .50 =       5.00
110072684    175 Gear         at     5.17 =     904.75

coweekly(2)->Description: Nut

coweekly[2] = gcnew OrderItem(...)

IndexOf(temp): 2

Remove(temp)

110072674    400 Widget       at    45.17 =  18,068.00
110072675     27 Sprocket     at     5.30 =     143.10
110072684    175 Gear         at     5.17 =     904.75

RemoveAt(0)

110072675     27 Sprocket     at     5.30 =     143.10
110072684    175 Gear         at     5.17 =     904.75
 */
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;

// This class represents a very simple keyed list of OrderItems,
// inheriting most of its behavior from the KeyedCollection and
// Collection classes. The immediate base class is the constructed
// type KeyedCollection<int, OrderItem>. When you inherit
// from KeyedCollection, the second generic type argument is the
// type that you want to store in the collection -- in this case
// OrderItem. The first type argument is the type that you want
// to use as a key. Its values must be calculated from OrderItem;
// in this case it is the int field PartNumber, so SimpleOrder
// inherits KeyedCollection<int, OrderItem>.
//
public class SimpleOrder : KeyedCollection<int, OrderItem>
{

    // This is the only method that absolutely must be overridden,
    // because without it the KeyedCollection cannot extract the
    // keys from the items. The input parameter type is the
    // second generic type argument, in this case OrderItem, and
    // the return value type is the first generic type argument,
    // in this case int.
    //
    protected override int GetKeyForItem(OrderItem item)
    {
        // In this example, the key is the part number.
        return item.PartNumber;
    }
}

public class Demo
{
    public static void Main()
    {
        SimpleOrder weekly = new SimpleOrder();

        // The Add method, inherited from Collection, takes OrderItem.
        //
        weekly.Add(new OrderItem(110072674, "Widget", 400, 45.17));
        weekly.Add(new OrderItem(110072675, "Sprocket", 27, 5.3));
        weekly.Add(new OrderItem(101030411, "Motor", 10, 237.5));
        weekly.Add(new OrderItem(110072684, "Gear", 175, 5.17));

        Display(weekly);

        // The Contains method of KeyedCollection takes the key,
        // type, in this case int.
        //
        Console.WriteLine("\nContains(101030411): {0}",
            weekly.Contains(101030411));

        // The default Item property of KeyedCollection takes a key.
        //
        Console.WriteLine("\nweekly[101030411].Description: {0}",
            weekly[101030411].Description);

        // The Remove method of KeyedCollection takes a key.
        //
        Console.WriteLine("\nRemove(101030411)");
        weekly.Remove(101030411);
        Display(weekly);

        // The Insert method, inherited from Collection, takes an
        // index and an OrderItem.
        //
        Console.WriteLine("\nInsert(2, New OrderItem(...))");
        weekly.Insert(2, new OrderItem(111033401, "Nut", 10, .5));
        Display(weekly);

        // The default Item property is overloaded. One overload comes
        // from KeyedCollection<int, OrderItem>; that overload
        // is read-only, and takes Integer because it retrieves by key.
        // The other overload comes from Collection<OrderItem>, the
        // base class of KeyedCollection<int, OrderItem>; it
        // retrieves by index, so it also takes an Integer. The compiler
        // uses the most-derived overload, from KeyedCollection, so the
        // only way to access SimpleOrder by index is to cast it to
        // Collection<OrderItem>. Otherwise the index is interpreted
        // as a key, and KeyNotFoundException is thrown.
        //
        Collection<OrderItem> coweekly = weekly;
        Console.WriteLine("\ncoweekly[2].Description: {0}",
            coweekly[2].Description);

        Console.WriteLine("\ncoweekly[2] = new OrderItem(...)");
        coweekly[2] = new OrderItem(127700026, "Crank", 27, 5.98);

        OrderItem temp = coweekly[2];

        // The IndexOf method inherited from Collection<OrderItem>
        // takes an OrderItem instead of a key
        //
        Console.WriteLine("\nIndexOf(temp): {0}", weekly.IndexOf(temp));

        // The inherited Remove method also takes an OrderItem.
        //
        Console.WriteLine("\nRemove(temp)");
        weekly.Remove(temp);
        Display(weekly);

        Console.WriteLine("\nRemoveAt(0)");
        weekly.RemoveAt(0);
        Display(weekly);
    }

    private static void Display(SimpleOrder order)
    {
        Console.WriteLine();
        foreach( OrderItem item in order )
        {
            Console.WriteLine(item);
        }
    }
}

// This class represents a simple line item in an order. All the
// values are immutable except quantity.
//
public class OrderItem
{
    public readonly int PartNumber;
    public readonly string Description;
    public readonly double UnitPrice;

    private int _quantity = 0;

    public OrderItem(int partNumber, string description,
        int quantity, double unitPrice)
    {
        this.PartNumber = partNumber;
        this.Description = description;
        this.Quantity = quantity;
        this.UnitPrice = unitPrice;
    }

    public int Quantity
    {
        get { return _quantity; }
        set
        {
            if (value<0)
                throw new ArgumentException("Quantity cannot be negative.");

            _quantity = value;
        }
    }

    public override string ToString()
    {
        return String.Format(
            "{0,9} {1,6} {2,-12} at {3,8:#,###.00} = {4,10:###,###.00}",
            PartNumber, _quantity, Description, UnitPrice,
            UnitPrice * _quantity);
    }
}

/* This code example produces the following output:

110072674    400 Widget       at    45.17 =  18,068.00
110072675     27 Sprocket     at     5.30 =     143.10
101030411     10 Motor        at   237.50 =   2,375.00
110072684    175 Gear         at     5.17 =     904.75

Contains(101030411): True

weekly[101030411].Description: Motor

Remove(101030411)

110072674    400 Widget       at    45.17 =  18,068.00
110072675     27 Sprocket     at     5.30 =     143.10
110072684    175 Gear         at     5.17 =     904.75

Insert(2, New OrderItem(...))

110072674    400 Widget       at    45.17 =  18,068.00
110072675     27 Sprocket     at     5.30 =     143.10
111033401     10 Nut          at      .50 =       5.00
110072684    175 Gear         at     5.17 =     904.75

coweekly[2].Description: Nut

coweekly[2] = new OrderItem(...)

IndexOf(temp): 2

Remove(temp)

110072674    400 Widget       at    45.17 =  18,068.00
110072675     27 Sprocket     at     5.30 =     143.10
110072684    175 Gear         at     5.17 =     904.75

RemoveAt(0)

110072675     27 Sprocket     at     5.30 =     143.10
110072684    175 Gear         at     5.17 =     904.75
 */
Imports System.Collections.Generic
Imports System.Collections.ObjectModel

' This class represents a very simple keyed list of OrderItems,
' inheriting most of its behavior from the KeyedCollection and 
' Collection classes. The immediate base class is the constructed
' type KeyedCollection(Of Integer, OrderItem). When you inherit
' from KeyedCollection, the second generic type argument is the 
' type that you want to store in the collection -- in this case
' OrderItem. The first generic argument is the type that you want
' to use as a key. Its values must be calculated from OrderItem; 
' in this case it is the Integer field PartNumber, so SimpleOrder
' inherits KeyedCollection(Of Integer, OrderItem).
'
Public Class SimpleOrder
    Inherits KeyedCollection(Of Integer, OrderItem)


    ' This is the only method that absolutely must be overridden,
    ' because without it the KeyedCollection cannot extract the
    ' keys from the items. The input parameter type is the 
    ' second generic type argument, in this case OrderItem, and 
    ' the return value type is the first generic type argument,
    ' in this case Integer.
    '
    Protected Overrides Function GetKeyForItem( _
        ByVal item As OrderItem) As Integer

        ' In this example, the key is the part number.
        Return item.PartNumber   
    End Function

End Class

Public Class Demo
    
    Public Shared Sub Main() 
        Dim weekly As New SimpleOrder()

        ' The Add method, inherited from Collection, takes OrderItem.
        '
        weekly.Add(New OrderItem(110072674, "Widget", 400, 45.17))
        weekly.Add(New OrderItem(110072675, "Sprocket", 27, 5.3))
        weekly.Add(New OrderItem(101030411, "Motor", 10, 237.5))
        weekly.Add(New OrderItem(110072684, "Gear", 175, 5.17))
        
        Display(weekly)
    
        ' The Contains method of KeyedCollection takes TKey.
        '
        Console.WriteLine(vbLf & "Contains(101030411): {0}", _
            weekly.Contains(101030411))

        ' The default Item property of KeyedCollection takes the key
        ' type, Integer.
        '
        Console.WriteLine(vbLf & "weekly(101030411).Description: {0}", _
            weekly(101030411).Description)

        ' The Remove method of KeyedCollection takes a key.
        '
        Console.WriteLine(vbLf & "Remove(101030411)")
        weekly.Remove(101030411)
        Display(weekly)

        ' The Insert method, inherited from Collection, takes an 
        ' index and an OrderItem.
        '
        Console.WriteLine(vbLf & "Insert(2, New OrderItem(...))")
        weekly.Insert(2, New OrderItem(111033401, "Nut", 10, .5))
        Display(weekly)

        ' The default Item property is overloaded. One overload comes
        ' from KeyedCollection(Of Integer, OrderItem); that overload
        ' is read-only, and takes Integer because it retrieves by key. 
        ' The other overload comes from Collection(Of OrderItem), the 
        ' base class of KeyedCollection(Of Integer, OrderItem); it 
        ' retrieves by index, so it also takes an Integer. The compiler
        ' uses the most-derived overload, from KeyedCollection, so the
        ' only way to access SimpleOrder by index is to cast it to
        ' Collection(Of OrderItem). Otherwise the index is interpreted
        ' as a key, and KeyNotFoundException is thrown.
        '
        Dim coweekly As Collection(Of OrderItem) = weekly
        Console.WriteLine(vbLf & "coweekly(2).Description: {0}", _
            coweekly(2).Description)
 
        Console.WriteLine(vbLf & "coweekly(2) = New OrderItem(...)")
        coweekly(2) = New OrderItem(127700026, "Crank", 27, 5.98)

        Dim temp As OrderItem = coweekly(2)

        ' The IndexOf method, inherited from Collection(Of OrderItem), 
        ' takes an OrderItem instead of a key.
        ' 
        Console.WriteLine(vbLf & "IndexOf(temp): {0}", _
            weekly.IndexOf(temp))

        ' The inherited Remove method also takes an OrderItem.
        '
        Console.WriteLine(vbLf & "Remove(temp)")
        weekly.Remove(temp)
        Display(weekly)

        Console.WriteLine(vbLf & "RemoveAt(0)")
        weekly.RemoveAt(0)
        Display(weekly)

    End Sub
    
    Private Shared Sub Display(ByVal order As SimpleOrder) 
        Console.WriteLine()
        For Each item As OrderItem In  order
            Console.WriteLine(item)
        Next item
    End Sub
End Class

' This class represents a simple line item in an order. All the 
' values are immutable except quantity.
' 
Public Class OrderItem
    Public ReadOnly PartNumber As Integer
    Public ReadOnly Description As String
    Public ReadOnly UnitPrice As Double
    
    Private _quantity As Integer = 0
    
    Public Sub New(ByVal partNumber As Integer, _
                   ByVal description As String, _
                   ByVal quantity As Integer, _
                   ByVal unitPrice As Double) 
        Me.PartNumber = partNumber
        Me.Description = description
        Me.Quantity = quantity
        Me.UnitPrice = unitPrice
    End Sub
    
    Public Property Quantity() As Integer 
        Get
            Return _quantity
        End Get
        Set
            If value < 0 Then
                Throw New ArgumentException("Quantity cannot be negative.")
            End If
            _quantity = value
        End Set
    End Property
        
    Public Overrides Function ToString() As String 
        Return String.Format( _
            "{0,9} {1,6} {2,-12} at {3,8:#,###.00} = {4,10:###,###.00}", _
            PartNumber, _quantity, Description, UnitPrice, _
            UnitPrice * _quantity)
    End Function
End Class

' This code example produces the following output:
'
'110072674    400 Widget       at    45.17 =  18,068.00
'110072675     27 Sprocket     at     5.30 =     143.10
'101030411     10 Motor        at   237.50 =   2,375.00
'110072684    175 Gear         at     5.17 =     904.75
'
'Contains(101030411): True
'
'weekly(101030411).Description: Motor
'
'Remove(101030411)
'
'110072674    400 Widget       at    45.17 =  18,068.00
'110072675     27 Sprocket     at     5.30 =     143.10
'110072684    175 Gear         at     5.17 =     904.75
'
'Insert(2, New OrderItem(...))
'
'110072674    400 Widget       at    45.17 =  18,068.00
'110072675     27 Sprocket     at     5.30 =     143.10
'111033401     10 Nut          at      .50 =       5.00
'110072684    175 Gear         at     5.17 =     904.75
'
'coweekly(2).Description: Nut
'
'coweekly(2) = New OrderItem(...)
'
'IndexOf(temp): 2
'
'Remove(temp)
'
'110072674    400 Widget       at    45.17 =  18,068.00
'110072675     27 Sprocket     at     5.30 =     143.10
'110072684    175 Gear         at     5.17 =     904.75
'
'RemoveAt(0)
'
'110072675     27 Sprocket     at     5.30 =     143.10
'110072684    175 Gear         at     5.17 =     904.75

範例 2

下列程式碼範例示範如何覆寫受保護的 、、 和 方法,以提供 、 RemoveClear 方法的自訂行為 Add ,以及在 C#) 中設定索引子的預設 Item[] 屬性 (。 SetItemClearItemsRemoveItemInsertItem 此範例中提供的自訂行為是名為 的 Changed 通知事件,會在每個覆寫方法的結尾引發。

此程式碼範例會 SimpleOrder 建立 衍生自 KeyedCollection<TKey,TItem> 的 類別,並代表簡單的順序表單。 順序表單包含 OrderItem 代表已排序專案的物件。 程式碼範例也會建立類別 SimpleOrderChangedEventArgs 來包含事件資訊,以及用來識別變更類型的列舉。

程式碼範例會藉由在 類別的 方法中 Main 呼叫衍生類別的屬性和方法 Demo ,來示範自訂行為。

此程式碼範例會使用具有不可變索引鍵的物件。 如需使用可變動索引鍵的程式碼範例,請參閱 ChangeItemKey

using namespace System;
using namespace System::Collections::Generic;
using namespace System::Collections::ObjectModel;

public enum class ChangeTypes
{
    Added,
    Removed, 
    Replaced, 
    Cleared
};

ref class SimpleOrderChangedEventArgs; 

// This class represents a simple line item in an order. All the 
// values are immutable except quantity.
// 
public ref class OrderItem
{
private:
    int _quantity;

public:
    initonly int PartNumber;
    initonly String^ Description;
    initonly double UnitPrice;
        
    OrderItem(int partNumber, String^ description, int quantity, 
        double unitPrice)
    {
        this->PartNumber = partNumber;
        this->Description = description;
        this->Quantity = quantity;
        this->UnitPrice = unitPrice;
    };
    
    property int Quantity    
    {
        int get() { return _quantity; };
        void set(int value)
        {
            if (value < 0)
                throw gcnew ArgumentException("Quantity cannot be negative.");
            
            _quantity = value;
        };
    };
        
    virtual String^ ToString() override 
    {
        return String::Format(
            "{0,9} {1,6} {2,-12} at {3,8:#,###.00} = {4,10:###,###.00}", 
            PartNumber, _quantity, Description, UnitPrice, 
            UnitPrice * _quantity);
    };
};

// Event argument for the Changed event.
//
public ref class SimpleOrderChangedEventArgs : EventArgs
{
public:
    OrderItem^ ChangedItem;
    initonly ChangeTypes ChangeType;
    OrderItem^ ReplacedWith;

    SimpleOrderChangedEventArgs(ChangeTypes change, 
        OrderItem^ item, OrderItem^ replacement)
    {
        this->ChangeType = change;
        this->ChangedItem = item;
        this->ReplacedWith = replacement;
    }
};

// This class derives from KeyedCollection and shows how to override
// the protected ClearItems, InsertItem, RemoveItem, and SetItem 
// methods in order to change the behavior of the default Item 
// property and the Add, Clear, Insert, and Remove methods. The
// class implements a Changed event, which is raised by all the
// protected methods.
//
// SimpleOrder is a collection of OrderItem objects, and its key
// is the PartNumber field of OrderItem-> PartNumber is an Integer,
// so SimpleOrder inherits KeyedCollection<int, OrderItem>.
// (Note that the key of OrderItem cannot be changed; if it could 
// be changed, SimpleOrder would have to override ChangeItemKey.)
//
public ref class SimpleOrder : KeyedCollection<int, OrderItem^>
{
public:
    event EventHandler<SimpleOrderChangedEventArgs^>^ Changed;

    // This parameterless constructor calls the base class constructor
    // that specifies a dictionary threshold of 0, so that the internal
    // dictionary is created as soon as an item is added to the 
    // collection.
    //
    SimpleOrder() : KeyedCollection<int, OrderItem^>(nullptr, 0) {};
    
    // This is the only method that absolutely must be overridden,
    // because without it the KeyedCollection cannot extract the
    // keys from the items. 
    //
protected:
    virtual int GetKeyForItem(OrderItem^ item) override
    {
        // In this example, the key is the part number.
        return item->PartNumber;
    }

    virtual void InsertItem(int index, OrderItem^ newItem) override 
    {
        __super::InsertItem(index, newItem);

        Changed(this, gcnew SimpleOrderChangedEventArgs(
            ChangeTypes::Added, newItem, nullptr));
    }

    virtual void SetItem(int index, OrderItem^ newItem) override 
    {
        OrderItem^ replaced = this->Items[index];
        __super::SetItem(index, newItem);

        Changed(this, gcnew SimpleOrderChangedEventArgs(
            ChangeTypes::Replaced, replaced, newItem));
    }

    virtual void RemoveItem(int index) override 
    {
        OrderItem^ removedItem = Items[index];
        __super::RemoveItem(index);

        Changed(this, gcnew SimpleOrderChangedEventArgs(
            ChangeTypes::Removed, removedItem, nullptr));
    }

    virtual void ClearItems() override 
    {
        __super::ClearItems();

        Changed(this, gcnew SimpleOrderChangedEventArgs(
            ChangeTypes::Cleared, nullptr, nullptr));
    }

    // This method uses the internal reference to the dictionary
    // to test fo
public:
    void AddOrMerge(OrderItem^ newItem)
    {

        int key = this->GetKeyForItem(newItem);
        OrderItem^ existingItem = nullptr;

        // The dictionary is not created until the first item is 
        // added, so it is necessary to test for null. Using 
        // AndAlso ensures that TryGetValue is not called if the
        // dictionary does not exist.
        //
        if (this->Dictionary != nullptr && 
            this->Dictionary->TryGetValue(key, existingItem))
        {
            existingItem->Quantity += newItem->Quantity;
        }
        else
        {
            this->Add(newItem);
        }
    }
};

public ref class Demo
{    
public:
    static void Main()
    {
        SimpleOrder^ weekly = gcnew SimpleOrder();
        weekly->Changed += gcnew 
            EventHandler<SimpleOrderChangedEventArgs^>(ChangedHandler);

        // The Add method, inherited from Collection, takes OrderItem->
        //
        weekly->Add(gcnew OrderItem(110072674, "Widget", 400, 45.17));
        weekly->Add(gcnew OrderItem(110072675, "Sprocket", 27, 5.3));
        weekly->Add(gcnew OrderItem(101030411, "Motor", 10, 237.5));
        weekly->Add(gcnew OrderItem(110072684, "Gear", 175, 5.17));

        Display(weekly);
        
        // The Contains method of KeyedCollection takes TKey.
        //
        Console::WriteLine("\nContains(101030411): {0}", 
            weekly->Contains(101030411));

        // The default Item property of KeyedCollection takes the key
        // type, Integer. The property is read-only.
        //
        Console::WriteLine("\nweekly[101030411]->Description: {0}", 
            weekly[101030411]->Description);

        // The Remove method of KeyedCollection takes a key.
        //
        Console::WriteLine("\nRemove(101030411)");
        weekly->Remove(101030411);

        // The Insert method, inherited from Collection, takes an 
        // index and an OrderItem.
        //
        Console::WriteLine("\nInsert(2, gcnew OrderItem(...))");
        weekly->Insert(2, gcnew OrderItem(111033401, "Nut", 10, .5));
         
        // The default Item property is overloaded. One overload comes
        // from KeyedCollection<int, OrderItem>; that overload
        // is read-only, and takes Integer because it retrieves by key. 
        // The other overload comes from Collection<OrderItem>, the 
        // base class of KeyedCollection<int, OrderItem>; it 
        // retrieves by index, so it also takes an Integer. The compiler
        // uses the most-derived overload, from KeyedCollection, so the
        // only way to access SimpleOrder by index is to cast it to
        // Collection<OrderItem>. Otherwise the index is interpreted
        // as a key, and KeyNotFoundException is thrown.
        //
        Collection<OrderItem^>^ coweekly = weekly;
        Console::WriteLine("\ncoweekly[2].Description: {0}", 
            coweekly[2]->Description);
 
        Console::WriteLine("\ncoweekly[2] = gcnew OrderItem(...)");
        coweekly[2] = gcnew OrderItem(127700026, "Crank", 27, 5.98);

        OrderItem^ temp = coweekly[2];

        // The IndexOf method, inherited from Collection<OrderItem>, 
        // takes an OrderItem instead of a key.
        // 
        Console::WriteLine("\nIndexOf(temp): {0}", weekly->IndexOf(temp));

        // The inherited Remove method also takes an OrderItem->
        //
        Console::WriteLine("\nRemove(temp)");
        weekly->Remove(temp);

        Console::WriteLine("\nRemoveAt(0)");
        weekly->RemoveAt(0);

        weekly->AddOrMerge(gcnew OrderItem(110072684, "Gear", 1000, 5.17));

        Display(weekly);

        Console::WriteLine();
        weekly->Clear();
    }
    
private:
    static void Display(SimpleOrder^ order)
    {
        Console::WriteLine();
        for each( OrderItem^ item in order )
        {
            Console::WriteLine(item);
        }
    }

    static void ChangedHandler(Object^ source, 
        SimpleOrderChangedEventArgs^ e)
    {
        OrderItem^ item = e->ChangedItem;

        if (e->ChangeType == ChangeTypes::Replaced)
        {
            OrderItem^ replacement = e->ReplacedWith;

            Console::WriteLine("{0} (quantity {1}) was replaced " +
                "by {2}, (quantity {3}).", item->Description, 
                item->Quantity, replacement->Description, 
                replacement->Quantity);
        }
        else if(e->ChangeType == ChangeTypes::Cleared)
        {
            Console::WriteLine("The order list was cleared.");
        }
        else
        {
            Console::WriteLine("{0} (quantity {1}) was {2}.", 
                item->Description, item->Quantity, e->ChangeType);
        }
    }
};

void main()
{
    Demo::Main();
}

/* This code example produces the following output:

Widget (quantity 400) was Added.
Sprocket (quantity 27) was Added.
Motor (quantity 10) was Added.
Gear (quantity 175) was Added.

110072674    400 Widget       at    45.17 =  18,068.00
110072675     27 Sprocket     at     5.30 =     143.10
101030411     10 Motor        at   237.50 =   2,375.00
110072684    175 Gear         at     5.17 =     904.75

Contains(101030411): True

weekly[101030411]->Description: Motor

Remove(101030411)
Motor (quantity 10) was Removed.

Insert(2, gcnew OrderItem(...))
Nut (quantity 10) was Added.

coweekly[2].Description: Nut

coweekly[2] = gcnew OrderItem(...)
Nut (quantity 10) was replaced by Crank, (quantity 27).

IndexOf(temp): 2

Remove(temp)
Crank (quantity 27) was Removed.

RemoveAt(0)
Widget (quantity 400) was Removed.

110072675     27 Sprocket     at     5.30 =     143.10
110072684   1175 Gear         at     5.17 =   6,074.75

The order list was cleared.
 */
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;

// This class derives from KeyedCollection and shows how to override
// the protected ClearItems, InsertItem, RemoveItem, and SetItem
// methods in order to change the behavior of the default Item
// property and the Add, Clear, Insert, and Remove methods. The
// class implements a Changed event, which is raised by all the
// protected methods.
//
// SimpleOrder is a collection of OrderItem objects, and its key
// is the PartNumber field of OrderItem. PartNumber is an Integer,
// so SimpleOrder inherits KeyedCollection<int, OrderItem>.
// (Note that the key of OrderItem cannot be changed; if it could
// be changed, SimpleOrder would have to override ChangeItemKey.)
//
public class SimpleOrder : KeyedCollection<int, OrderItem>
{
    public event EventHandler<SimpleOrderChangedEventArgs> Changed;

    // This parameterless constructor calls the base class constructor
    // that specifies a dictionary threshold of 0, so that the internal
    // dictionary is created as soon as an item is added to the
    // collection.
    //
    public SimpleOrder() : base(null, 0) {}

    // This is the only method that absolutely must be overridden,
    // because without it the KeyedCollection cannot extract the
    // keys from the items.
    //
    protected override int GetKeyForItem(OrderItem item)
    {
        // In this example, the key is the part number.
        return item.PartNumber;
    }

    protected override void InsertItem(int index, OrderItem newItem)
    {
        base.InsertItem(index, newItem);

        EventHandler<SimpleOrderChangedEventArgs> temp = Changed;
        if (temp != null)
        {
            temp(this, new SimpleOrderChangedEventArgs(
                ChangeType.Added, newItem, null));
        }
    }

    protected override void SetItem(int index, OrderItem newItem)
    {
        OrderItem replaced = Items[index];
        base.SetItem(index, newItem);

        EventHandler<SimpleOrderChangedEventArgs> temp = Changed;
        if (temp != null)
        {
            temp(this, new SimpleOrderChangedEventArgs(
                ChangeType.Replaced, replaced, newItem));
        }
    }

    protected override void RemoveItem(int index)
    {
        OrderItem removedItem = Items[index];
        base.RemoveItem(index);

        EventHandler<SimpleOrderChangedEventArgs> temp = Changed;
        if (temp != null)
        {
            temp(this, new SimpleOrderChangedEventArgs(
                ChangeType.Removed, removedItem, null));
        }
    }

    protected override void ClearItems()
    {
        base.ClearItems();

        EventHandler<SimpleOrderChangedEventArgs> temp = Changed;
        if (temp != null)
        {
            temp(this, new SimpleOrderChangedEventArgs(
                ChangeType.Cleared, null, null));
        }
    }
}

// Event argument for the Changed event.
//
public class SimpleOrderChangedEventArgs : EventArgs
{
    private OrderItem _changedItem;
    private ChangeType _changeType;
    private OrderItem _replacedWith;

    public OrderItem ChangedItem { get { return _changedItem; }}
    public ChangeType ChangeType { get { return _changeType; }}
    public OrderItem ReplacedWith { get { return _replacedWith; }}

    public SimpleOrderChangedEventArgs(ChangeType change,
        OrderItem item, OrderItem replacement)
    {
        _changeType = change;
        _changedItem = item;
        _replacedWith = replacement;
    }
}

public enum ChangeType
{
    Added,
    Removed,
    Replaced,
    Cleared
};

public class Demo
{
    public static void Main()
    {
        SimpleOrder weekly = new SimpleOrder();
        weekly.Changed += new
            EventHandler<SimpleOrderChangedEventArgs>(ChangedHandler);

        // The Add method, inherited from Collection, takes OrderItem.
        //
        weekly.Add(new OrderItem(110072674, "Widget", 400, 45.17));
        weekly.Add(new OrderItem(110072675, "Sprocket", 27, 5.3));
        weekly.Add(new OrderItem(101030411, "Motor", 10, 237.5));
        weekly.Add(new OrderItem(110072684, "Gear", 175, 5.17));

        Display(weekly);

        // The Contains method of KeyedCollection takes TKey.
        //
        Console.WriteLine("\nContains(101030411): {0}",
            weekly.Contains(101030411));

        // The default Item property of KeyedCollection takes the key
        // type, Integer. The property is read-only.
        //
        Console.WriteLine("\nweekly[101030411].Description: {0}",
            weekly[101030411].Description);

        // The Remove method of KeyedCollection takes a key.
        //
        Console.WriteLine("\nRemove(101030411)");
        weekly.Remove(101030411);

        // The Insert method, inherited from Collection, takes an
        // index and an OrderItem.
        //
        Console.WriteLine("\nInsert(2, new OrderItem(...))");
        weekly.Insert(2, new OrderItem(111033401, "Nut", 10, .5));

        // The default Item property is overloaded. One overload comes
        // from KeyedCollection<int, OrderItem>; that overload
        // is read-only, and takes Integer because it retrieves by key.
        // The other overload comes from Collection<OrderItem>, the
        // base class of KeyedCollection<int, OrderItem>; it
        // retrieves by index, so it also takes an Integer. The compiler
        // uses the most-derived overload, from KeyedCollection, so the
        // only way to access SimpleOrder by index is to cast it to
        // Collection<OrderItem>. Otherwise the index is interpreted
        // as a key, and KeyNotFoundException is thrown.
        //
        Collection<OrderItem> coweekly = weekly;
        Console.WriteLine("\ncoweekly[2].Description: {0}",
            coweekly[2].Description);

        Console.WriteLine("\ncoweekly[2] = new OrderItem(...)");
        coweekly[2] = new OrderItem(127700026, "Crank", 27, 5.98);

        OrderItem temp = coweekly[2];

        // The IndexOf method, inherited from Collection<OrderItem>,
        // takes an OrderItem instead of a key.
        //
        Console.WriteLine("\nIndexOf(temp): {0}", weekly.IndexOf(temp));

        // The inherited Remove method also takes an OrderItem.
        //
        Console.WriteLine("\nRemove(temp)");
        weekly.Remove(temp);

        Console.WriteLine("\nRemoveAt(0)");
        weekly.RemoveAt(0);

        // Increase the quantity for a line item.
        Console.WriteLine("\ncoweekly(1) = New OrderItem(...)");
        coweekly[1] = new OrderItem(coweekly[1].PartNumber,
            coweekly[1].Description, coweekly[1].Quantity + 1000,
            coweekly[1].UnitPrice);

        Display(weekly);

        Console.WriteLine();
        weekly.Clear();
    }

    private static void Display(SimpleOrder order)
    {
        Console.WriteLine();
        foreach( OrderItem item in order )
        {
            Console.WriteLine(item);
        }
    }

    private static void ChangedHandler(object source,
        SimpleOrderChangedEventArgs e)
    {

        OrderItem item = e.ChangedItem;

        if (e.ChangeType==ChangeType.Replaced)
        {
            OrderItem replacement = e.ReplacedWith;

            Console.WriteLine("{0} (quantity {1}) was replaced " +
                "by {2}, (quantity {3}).", item.Description,
                item.Quantity, replacement.Description,
                replacement.Quantity);
        }
        else if(e.ChangeType == ChangeType.Cleared)
        {
            Console.WriteLine("The order list was cleared.");
        }
        else
        {
            Console.WriteLine("{0} (quantity {1}) was {2}.",
                item.Description, item.Quantity, e.ChangeType);
        }
    }
}

// This class represents a simple line item in an order. All the
// values are immutable except quantity.
//
public class OrderItem
{
    private int _partNumber;
    private string _description;
    private double _unitPrice;
    private int _quantity;

    public int PartNumber { get { return _partNumber; }}
    public string Description { get { return _description; }}
    public double UnitPrice { get { return _unitPrice; }}
    public int Quantity { get { return _quantity; }}

    public OrderItem(int partNumber, string description, int quantity,
        double unitPrice)
    {
        _partNumber = partNumber;
        _description = description;
        _quantity = quantity;
        _unitPrice = unitPrice;
    }

    public override string ToString()
    {
        return String.Format(
            "{0,9} {1,6} {2,-12} at {3,8:#,###.00} = {4,10:###,###.00}",
            PartNumber, _quantity, Description, UnitPrice,
            UnitPrice * _quantity);
    }
}

/* This code example produces the following output:

Widget (quantity 400) was Added.
Sprocket (quantity 27) was Added.
Motor (quantity 10) was Added.
Gear (quantity 175) was Added.

110072674    400 Widget       at    45.17 =  18,068.00
110072675     27 Sprocket     at     5.30 =     143.10
101030411     10 Motor        at   237.50 =   2,375.00
110072684    175 Gear         at     5.17 =     904.75

Contains(101030411): True

weekly[101030411].Description: Motor

Remove(101030411)
Motor (quantity 10) was Removed.

Insert(2, new OrderItem(...))
Nut (quantity 10) was Added.

coweekly[2].Description: Nut

coweekly[2] = new OrderItem(...)
Nut (quantity 10) was replaced by Crank, (quantity 27).

IndexOf(temp): 2

Remove(temp)
Crank (quantity 27) was Removed.

RemoveAt(0)
Widget (quantity 400) was Removed.

coweekly(1) = New OrderItem(...)
Gear (quantity 175) was replaced by Gear, (quantity 1175).

110072675     27 Sprocket     at     5.30 =     143.10
110072684   1175 Gear         at     5.17 =   6,074.75

The order list was cleared.
 */
Imports System.Collections.Generic
Imports System.Collections.ObjectModel

' This class derives from KeyedCollection and shows how to override
' the protected ClearItems, InsertItem, RemoveItem, and SetItem 
' methods in order to change the behavior of the default Item 
' property and the Add, Clear, Insert, and Remove methods. The
' class implements a Changed event, which is raised by all the
' protected methods.
'
' SimpleOrder is a collection of OrderItem objects, and its key
' is the PartNumber field of OrderItem. PartNumber is an Integer,
' so SimpleOrder inherits KeyedCollection(Of Integer, OrderItem).
' (Note that the key of OrderItem cannot be changed; if it could 
' be changed, SimpleOrder would have to override ChangeItemKey.)
'
Public Class SimpleOrder
    Inherits KeyedCollection(Of Integer, OrderItem)

    Public Event Changed As EventHandler(Of SimpleOrderChangedEventArgs)

    ' This parameterless constructor calls the base class constructor
    ' that specifies a dictionary threshold of 0, so that the internal
    ' dictionary is created as soon as an item is added to the 
    ' collection.
    '
    Public Sub New()
        MyBase.New(Nothing, 0)
    End Sub
    
    ' This is the only method that absolutely must be overridden,
    ' because without it the KeyedCollection cannot extract the
    ' keys from the items. 
    '
    Protected Overrides Function GetKeyForItem( _
        ByVal item As OrderItem) As Integer

        ' In this example, the key is the part number.
        Return item.PartNumber   
    End Function

    Protected Overrides Sub InsertItem( _
        ByVal index As Integer, ByVal newItem As OrderItem)

        MyBase.InsertItem(index, newItem)

        RaiseEvent Changed(Me, New SimpleOrderChangedEventArgs( _
            ChangeType.Added, newItem, Nothing))
    End Sub

    Protected Overrides Sub SetItem(ByVal index As Integer, _
        ByVal newItem As OrderItem)

        Dim replaced As OrderItem = Items(index)
        MyBase.SetItem(index, newItem)

        RaiseEvent Changed(Me, New SimpleOrderChangedEventArgs( _
            ChangeType.Replaced, replaced, newItem))
    End Sub

    Protected Overrides Sub RemoveItem(ByVal index As Integer)

        Dim removedItem As OrderItem = Items(index)
        MyBase.RemoveItem(index)

        RaiseEvent Changed(Me, New SimpleOrderChangedEventArgs( _
            ChangeType.Removed, removedItem, Nothing))
    End Sub

    Protected Overrides Sub ClearItems()
        MyBase.ClearItems()

        RaiseEvent Changed(Me, New SimpleOrderChangedEventArgs( _
            ChangeType.Cleared, Nothing, Nothing))
    End Sub

End Class

' Event argument for the Changed event.
'
Public Class SimpleOrderChangedEventArgs
    Inherits EventArgs

    Private _changedItem As OrderItem
    Private _changeType As ChangeType
    Private _replacedWith As OrderItem

    Public ReadOnly Property ChangedItem As OrderItem
        Get
            Return _changedItem
        End Get
    End Property

    Public ReadOnly Property ChangeType As ChangeType
        Get
            Return _changeType
        End Get
    End Property

    Public ReadOnly Property ReplacedWith As OrderItem
        Get
            Return _replacedWith
        End Get
    End Property

    Public Sub New(ByVal change As ChangeType, ByVal item As OrderItem, _
        ByVal replacement As OrderItem)

        _changeType = change
        _changedItem = item
        _replacedWith = replacement
    End Sub
End Class

Public Enum ChangeType
    Added
    Removed
    Replaced
    Cleared
End Enum

Public Class Demo
    
    Public Shared Sub Main() 
        Dim weekly As New SimpleOrder()
        AddHandler weekly.Changed, AddressOf ChangedHandler

        ' The Add method, inherited from Collection, takes OrderItem.
        '
        weekly.Add(New OrderItem(110072674, "Widget", 400, 45.17))
        weekly.Add(New OrderItem(110072675, "Sprocket", 27, 5.3))
        weekly.Add(New OrderItem(101030411, "Motor", 10, 237.5))
        weekly.Add(New OrderItem(110072684, "Gear", 175, 5.17))

        Display(weekly)
        
        ' The Contains method of KeyedCollection takes TKey.
        '
        Console.WriteLine(vbLf & "Contains(101030411): {0}", _
            weekly.Contains(101030411))

        ' The default Item property of KeyedCollection takes the key
        ' type, Integer. The property is read-only.
        '
        Console.WriteLine(vbLf & "weekly(101030411).Description: {0}", _
            weekly(101030411).Description)

        ' The Remove method of KeyedCollection takes a key.
        '
        Console.WriteLine(vbLf & "Remove(101030411)")
        weekly.Remove(101030411)

        ' The Insert method, inherited from Collection, takes an 
        ' index and an OrderItem.
        '
        Console.WriteLine(vbLf & "Insert(2, New OrderItem(...))")
        weekly.Insert(2, New OrderItem(111033401, "Nut", 10, .5))
         
        ' The default Item property is overloaded. One overload comes
        ' from KeyedCollection(Of Integer, OrderItem); that overload
        ' is read-only, and takes Integer because it retrieves by key. 
        ' The other overload comes from Collection(Of OrderItem), the 
        ' base class of KeyedCollection(Of Integer, OrderItem); it 
        ' retrieves by index, so it also takes an Integer. The compiler
        ' uses the most-derived overload, from KeyedCollection, so the
        ' only way to access SimpleOrder by index is to cast it to
        ' Collection(Of OrderItem). Otherwise the index is interpreted
        ' as a key, and KeyNotFoundException is thrown.
        '
        Dim coweekly As Collection(Of OrderItem) = weekly
        Console.WriteLine(vbLf & "coweekly(2).Description: {0}", _
            coweekly(2).Description)
 
        Console.WriteLine(vbLf & "coweekly(2) = New OrderItem(...)")
        coweekly(2) = New OrderItem(127700026, "Crank", 27, 5.98)

        Dim temp As OrderItem = coweekly(2)

        ' The IndexOf method, inherited from Collection(Of OrderItem), 
        ' takes an OrderItem instead of a key.
        ' 
        Console.WriteLine(vbLf & "IndexOf(temp): {0}", _
            weekly.IndexOf(temp))

        ' The inherited Remove method also takes an OrderItem.
        '
        Console.WriteLine(vbLf & "Remove(temp)")
        weekly.Remove(temp)

        Console.WriteLine(vbLf & "RemoveAt(0)")
        weekly.RemoveAt(0)

        ' Increase the quantity for a line item.
        Console.WriteLine(vbLf & "coweekly(1) = New OrderItem(...)")
        coweekly(1) = New OrderItem(coweekly(1).PartNumber, _
            coweekly(1).Description, coweekly(1).Quantity + 1000, _
            coweekly(1).UnitPrice)

        Display(weekly)

        Console.WriteLine()
        weekly.Clear()
    End Sub
    
    Private Shared Sub Display(ByVal order As SimpleOrder) 
        Console.WriteLine()
        For Each item As OrderItem In  order
            Console.WriteLine(item)
        Next item
    End Sub

    Private Shared Sub ChangedHandler(ByVal source As Object, _
        ByVal e As SimpleOrderChangedEventArgs)

        Dim item As OrderItem = e.ChangedItem

        If e.ChangeType = ChangeType.Replaced Then
            Dim replacement As OrderItem = e.ReplacedWith

            Console.WriteLine("{0} (quantity {1}) was replaced " & _
                "by {2}, (quantity {3}).", item.Description, _
                item.Quantity, replacement.Description, replacement.Quantity)

        ElseIf e.ChangeType = ChangeType.Cleared Then
            Console.WriteLine("The order list was cleared.")

        Else
            Console.WriteLine("{0} (quantity {1}) was {2}.", _
                item.Description, item.Quantity, e.ChangeType)
        End If
    End Sub
End Class

' This class represents a simple line item in an order. All the 
' values are immutable except quantity.
' 
Public Class OrderItem
    
    Private _partNumber As Integer
    Private _description As String
    Private _unitPrice As Double
    Private _quantity As Integer

    Public ReadOnly Property PartNumber As Integer
        Get
            Return _partNumber
        End Get
    End Property

    Public ReadOnly Property Description As String
        Get
            Return _description
        End Get
    End Property

    Public ReadOnly Property UnitPrice As Double
        Get
            Return _unitPrice
        End Get
    End Property
    
    Public ReadOnly Property Quantity() As Integer 
        Get
            Return _quantity
        End Get
    End Property
    
    Public Sub New(ByVal partNumber As Integer, _
                   ByVal description As String, _
                   ByVal quantity As Integer, _
                   ByVal unitPrice As Double) 
        _partNumber = partNumber
        _description = description
        _quantity = quantity
        _unitPrice = unitPrice
    End Sub
        
    Public Overrides Function ToString() As String 
        Return String.Format( _
            "{0,9} {1,6} {2,-12} at {3,8:#,###.00} = {4,10:###,###.00}", _
            PartNumber, _quantity, Description, UnitPrice, _
            UnitPrice * _quantity)
    End Function
End Class

' This code example produces the following output:
'
'Widget (quantity 400) was Added.
'Sprocket (quantity 27) was Added.
'Motor (quantity 10) was Added.
'Gear (quantity 175) was Added.
'
'110072674    400 Widget       at    45.17 =  18,068.00
'110072675     27 Sprocket     at     5.30 =     143.10
'101030411     10 Motor        at   237.50 =   2,375.00
'110072684    175 Gear         at     5.17 =     904.75
'
'Contains(101030411): True
'
'weekly(101030411).Description: Motor
'
'Remove(101030411)
'Motor (quantity 10) was Removed.
'
'Insert(2, New OrderItem(...))
'Nut (quantity 10) was Added.
'
'coweekly(2).Description: Nut
'
'coweekly(2) = New OrderItem(...)
'Nut (quantity 10) was replaced by Crank, (quantity 27).
'
'IndexOf(temp): 2
'
'Remove(temp)
'Crank (quantity 27) was Removed.
'
'RemoveAt(0)
'Widget (quantity 400) was Removed.
'
'coweekly(1) = New OrderItem(...)
'Gear (quantity 175) was replaced by Gear, (quantity 1175).
'
'110072675     27 Sprocket     at     5.30 =     143.10
'110072684   1175 Gear         at     5.17 =   6,074.75
'
'The order list was cleared.

備註

類別 KeyedCollection<TKey,TItem> 提供 O (1) 索引擷取,以及接近 O (1) 的索引擷取。 它是抽象類別型,或更精確地是一組無限的抽象類別型,因為每個建構的泛型型別都是抽象基類。 若要使用 KeyedCollection<TKey,TItem> ,請從適當的建構型別衍生您的集合類型。

類別 KeyedCollection<TKey,TItem> 是根據泛型介面的集合 IList<T> 和以泛型介面為基礎的 IDictionary<TKey,TValue> 集合之間的混合式。 如同以泛型介面為基礎的 IList<T> 集合, KeyedCollection<TKey,TItem> 是專案的索引清單。 如同以泛型介面為基礎的 IDictionary<TKey,TValue> 集合, KeyedCollection<TKey,TItem> 具有與每個元素相關聯的索引鍵。

不同于字典,的 KeyedCollection<TKey,TItem> 元素不是索引鍵/值組,而是整個元素是值,而索引鍵會內嵌在值內。 例如,衍生自 KeyedCollection\<String,String> Visual Basic) 中 (KeyedCollection(Of String, String) 集合的專案可能是 「John Doe Jr」。其中值是 「John Doe Jr」。而索引鍵是 「Doe」;或者包含整數索引鍵的員工記錄集合可能衍生自 KeyedCollection\<int,Employee> 。 抽象 GetKeyForItem 方法會從 專案擷取索引鍵。

根據預設,包含 KeyedCollection<TKey,TItem> 您可以使用 屬性取得的 Dictionary 查閱字典。 將專案新增至 KeyedCollection<TKey,TItem> 時,專案的索引鍵會擷取一次,並儲存在查閱字典中,以取得更快速的搜尋。 當您建立 KeyedCollection<TKey,TItem> 時,藉由指定字典建立臨界值來覆寫此行為。 查閱字典會在第一次超過該臨界值時建立。 如果您將 -1 指定為臨界值,則永遠不會建立查閱字典。

注意

使用內部查閱字典時,如果 TItem 是參考型別,則包含集合中所有專案的參考,如果 TItem 是實值型別,則包含集合中所有專案的複本。 因此,如果 TItem 為實值型別,則使用查閱字典可能不適用。

您可以使用 屬性,依專案的索引或索引鍵 Item[] 來存取專案。 您可以新增沒有索引鍵的專案,但後續只能透過索引存取這些專案。

建構函式

KeyedCollection<TKey,TItem>()

初始化 KeyedCollection<TKey,TItem> 類別的新執行個體,此執行個體使用預設的等號比較子。

KeyedCollection<TKey,TItem>(IEqualityComparer<TKey>)

初始化 KeyedCollection<TKey,TItem> 類別的新執行個體,此執行個體使用指定的等號比較子。

KeyedCollection<TKey,TItem>(IEqualityComparer<TKey>, Int32)

初始化 KeyedCollection<TKey,TItem> 類別的新執行個體,此執行個體使用指定的等號比較子,並在超過指定的臨界值時,建立查閱字典。

屬性

Comparer

取得用來判斷集合中索引鍵是否相等的泛型等號比較子。

Count

取得 Collection<T> 中實際包含的項目數目。

(繼承來源 Collection<T>)
Dictionary

取得 KeyedCollection<TKey,TItem> 的查閱字典。

Item[Int32]

在指定的索引位置上取得或設定項目。

(繼承來源 Collection<T>)
Item[TKey]

取得具有指定索引鍵的項目。

Items

取得 IList<T> 周圍的 Collection<T> 包裝函式。

(繼承來源 Collection<T>)

方法

Add(T)

將物件加入至 Collection<T> 的末端。

(繼承來源 Collection<T>)
ChangeItemKey(TItem, TKey)

變更查閱字典中與指定的項目相關的索引鍵。

Clear()

移除 Collection<T> 中的所有項目。

(繼承來源 Collection<T>)
ClearItems()

移除 KeyedCollection<TKey,TItem> 中的所有項目。

Contains(TKey)

判斷集合是否包含具有指定之索引鍵的項目。

CopyTo(T[], Int32)

從目標陣列的指定索引開始,將整個 Collection<T> 複製到相容的一維 Array

(繼承來源 Collection<T>)
Equals(Object)

判斷指定的物件是否等於目前的物件。

(繼承來源 Object)
GetEnumerator()

傳回在 Collection<T> 中逐一查看的列舉值。

(繼承來源 Collection<T>)
GetHashCode()

做為預設雜湊函式。

(繼承來源 Object)
GetKeyForItem(TItem)

在衍生類別中實作時,從指定的項目擷取索引鍵。

GetType()

取得目前執行個體的 Type

(繼承來源 Object)
IndexOf(T)

搜尋指定的物件,並傳回整個 Collection<T> 中第一個出現之以零為起始的索引。

(繼承來源 Collection<T>)
Insert(Int32, T)

將項目插入至 Collection<T> 中指定的索引位置。

(繼承來源 Collection<T>)
InsertItem(Int32, T)

將項目插入至 Collection<T> 中指定的索引位置。

(繼承來源 Collection<T>)
InsertItem(Int32, TItem)

將項目插入至 KeyedCollection<TKey,TItem> 中指定的索引位置。

MemberwiseClone()

建立目前 Object 的淺層複製。

(繼承來源 Object)
Remove(TKey)

KeyedCollection<TKey,TItem> 中移除具有指定之索引鍵的項目。

RemoveAt(Int32)

移除 Collection<T> 之指定索引處的項目。

(繼承來源 Collection<T>)
RemoveItem(Int32)

移除 KeyedCollection<TKey,TItem> 之指定索引處的項目。

SetItem(Int32, T)

取代指定之索引處的項目。

(繼承來源 Collection<T>)
SetItem(Int32, TItem)

以指定的項目取代位於指定索引上的項目。

ToString()

傳回代表目前物件的字串。

(繼承來源 Object)
TryGetValue(TKey, TItem)

使用指定的索引鍵嘗試取得集合中項目。

明確介面實作

ICollection.CopyTo(Array, Int32)

從特定的 ICollection 索引開始,將 Array 的項目複製到 Array

(繼承來源 Collection<T>)
ICollection.IsSynchronized

取得值,這個值表示對 ICollection 的存取是否同步 (安全執行緒)。

(繼承來源 Collection<T>)
ICollection.SyncRoot

取得可用以同步存取 ICollection 的物件。

(繼承來源 Collection<T>)
ICollection<T>.IsReadOnly

取得值,指出 ICollection<T> 是否唯讀。

(繼承來源 Collection<T>)
IEnumerable.GetEnumerator()

傳回逐一查看集合的列舉值。

(繼承來源 Collection<T>)
IList.Add(Object)

將項目加入至 IList

(繼承來源 Collection<T>)
IList.Contains(Object)

判斷 IList 是否包含特定值。

(繼承來源 Collection<T>)
IList.IndexOf(Object)

判斷 IList 中指定項目的索引。

(繼承來源 Collection<T>)
IList.Insert(Int32, Object)

將項目插入 IList 中指定的索引處。

(繼承來源 Collection<T>)
IList.IsFixedSize

取得值,指出 IList 是否有固定的大小。

(繼承來源 Collection<T>)
IList.IsReadOnly

取得值,指出 IList 是否唯讀。

(繼承來源 Collection<T>)
IList.Item[Int32]

在指定的索引位置上取得或設定項目。

(繼承來源 Collection<T>)
IList.Remove(Object)

IList 移除特定物件之第一個符合的元素。

(繼承來源 Collection<T>)

擴充方法

ToFrozenDictionary<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>, IEqualityComparer<TKey>)

FrozenDictionary<TKey,TValue>根據指定的索引鍵選取器函式,從 IEnumerable<T> 建立 。

ToFrozenDictionary<TSource,TKey,TElement>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TElement>, IEqualityComparer<TKey>)

根據指定的索引鍵選取器和項目選取器函式,從 FrozenDictionary<TKey,TValue> 建立 IEnumerable<T>

ToFrozenSet<T>(IEnumerable<T>, IEqualityComparer<T>)

FrozenSet<T>使用指定的值建立 。

AsReadOnly<T>(IList<T>)

傳回指定清單的唯讀 ReadOnlyCollection<T> 包裝函式。

ToImmutableArray<TSource>(IEnumerable<TSource>)

從指定的集合建立不可變的陣列。

ToImmutableDictionary<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>)

從現有的項目集合建構不可變的字典,將轉換函式套用至來源索引鍵。

ToImmutableDictionary<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>, IEqualityComparer<TKey>)

根據序列的某些轉換來建構不可變的字典。

ToImmutableDictionary<TSource,TKey,TValue>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TValue>)

列舉及轉換序列,並產生其內容的不可變字典。

ToImmutableDictionary<TSource,TKey,TValue>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TValue>, IEqualityComparer<TKey>)

列舉及轉換序列,並使用指定的索引鍵比較子產生其內容的不可變字典。

ToImmutableDictionary<TSource,TKey,TValue>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TValue>, IEqualityComparer<TKey>, IEqualityComparer<TValue>)

列舉及轉換序列,並使用指定的索引鍵與值比較子產生其內容的不可變字典。

ToImmutableHashSet<TSource>(IEnumerable<TSource>)

列舉序列,並產生其內容之不可變雜湊集。

ToImmutableHashSet<TSource>(IEnumerable<TSource>, IEqualityComparer<TSource>)

列舉序列、產生其內容之不可變雜湊集,且針對集合類型使用指定的相等比較子。

ToImmutableList<TSource>(IEnumerable<TSource>)

列舉序列,並產生其內容的不可變清單。

ToImmutableSortedDictionary<TSource,TKey,TValue>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TValue>)

列舉及轉換序列,並產生不可變的排序字典作為內容。

ToImmutableSortedDictionary<TSource,TKey,TValue>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TValue>, IComparer<TKey>)

列舉及轉換序列,並使用指定的索引鍵比較子產生不可變的排序字典作為內容。

ToImmutableSortedDictionary<TSource,TKey,TValue>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TValue>, IComparer<TKey>, IEqualityComparer<TValue>)

列舉及轉換序列,並使用指定的索引鍵與值比較子產生不可變的排序字典作為內容。

ToImmutableSortedSet<TSource>(IEnumerable<TSource>)

列舉序列,並產生其內容的不可變排序資料集。

ToImmutableSortedSet<TSource>(IEnumerable<TSource>, IComparer<TSource>)

列舉序列、產生其內容的不可變排序資料集,並使用指定的比較子。

CopyToDataTable<T>(IEnumerable<T>)

根據輸入 DataTable 物件 (其中泛型參數 TDataRow) 傳回包含 IEnumerable<T> 物件複本的 DataRow

CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption)

根據輸入 DataRow 物件 (其中泛型參數 TDataTable),將 IEnumerable<T> 物件複製到指定的 DataRow

CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption, FillErrorEventHandler)

根據輸入 DataRow 物件 (其中泛型參數 TDataTable),將 IEnumerable<T> 物件複製到指定的 DataRow

Aggregate<TSource>(IEnumerable<TSource>, Func<TSource,TSource,TSource>)

將累加函式套用到序列上。

Aggregate<TSource,TAccumulate>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate,TSource,TAccumulate>)

將累加函式套用到序列上。 使用指定的初始值做為初始累加值。

Aggregate<TSource,TAccumulate,TResult>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate,TSource,TAccumulate>, Func<TAccumulate,TResult>)

將累加函式套用到序列上。 使用指定的值做為初始累加值,並使用指定的函式來選取結果值。

AggregateBy<TSource,TKey,TAccumulate>(IEnumerable<TSource>, Func<TSource, TKey>, TAccumulate, Func<TAccumulate,TSource,TAccumulate>, IEqualityComparer<TKey>)

為內嵌在值之索引鍵的集合,提供抽象基底類別。

AggregateBy<TSource,TKey,TAccumulate>(IEnumerable<TSource>, Func<TSource, TKey>, Func<TKey,TAccumulate>, Func<TAccumulate,TSource,TAccumulate>, IEqualityComparer<TKey>)

為內嵌在值之索引鍵的集合,提供抽象基底類別。

All<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)

判斷序列的所有項目是否全都符合條件。

Any<TSource>(IEnumerable<TSource>)

判斷序列是否包含任何項目。

Any<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)

判斷序列的任何項目是否符合條件。

Append<TSource>(IEnumerable<TSource>, TSource)

將值附加在序列結尾。

AsEnumerable<TSource>(IEnumerable<TSource>)

傳回 IEnumerable<T> 類型的輸入。

Average<TSource>(IEnumerable<TSource>, Func<TSource,Decimal>)

計算在輸入序列中各項目上叫用轉換函式後所取得之 Decimal 值序列的平均值。

Average<TSource>(IEnumerable<TSource>, Func<TSource,Double>)

計算在輸入序列中各項目上叫用轉換函式後所取得之 Double 值序列的平均值。

Average<TSource>(IEnumerable<TSource>, Func<TSource,Int32>)

計算在輸入序列中各項目上叫用轉換函式後所取得之 Int32 值序列的平均值。

Average<TSource>(IEnumerable<TSource>, Func<TSource,Int64>)

計算在輸入序列中各項目上叫用轉換函式後所取得之 Int64 值序列的平均值。

Average<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Decimal>>)

計算在輸入序列中各項目上叫用轉換函式後所取得可為 Null 之 Decimal 值的平均值。

Average<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Double>>)

計算在輸入序列中各項目上叫用轉換函式後所取得可為 Null 之 Double 值的平均值。

Average<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Int32>>)

計算在輸入序列中各項目上叫用轉換函式後所取得可為 Null 之 Int32 值的平均值。

Average<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Int64>>)

計算在輸入序列中各項目上叫用轉換函式後所取得可為 Null 之 Int64 值的平均值。

Average<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Single>>)

計算在輸入序列中各項目上叫用轉換函式後所取得可為 Null 之 Single 值的平均值。

Average<TSource>(IEnumerable<TSource>, Func<TSource,Single>)

計算在輸入序列中各項目上叫用轉換函式後所取得之 Single 值序列的平均值。

Cast<TResult>(IEnumerable)

IEnumerable 的項目轉換成指定的型別。

Chunk<TSource>(IEnumerable<TSource>, Int32)

將序列的專案分割成大小上限 size 的區塊。

Concat<TSource>(IEnumerable<TSource>, IEnumerable<TSource>)

串連兩個序列。

Contains<TSource>(IEnumerable<TSource>, TSource)

使用預設的相等比較子 (Comparer) 來判斷序列是否包含指定的項目。

Contains<TSource>(IEnumerable<TSource>, TSource, IEqualityComparer<TSource>)

使用指定的 IEqualityComparer<T> 來判斷序列是否包含指定的項目。

Count<TSource>(IEnumerable<TSource>)

傳回序列中的項目數。

Count<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)

傳回數字,代表指定之序列中符合條件的項目數目。

CountBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>, IEqualityComparer<TKey>)

為內嵌在值之索引鍵的集合,提供抽象基底類別。

DefaultIfEmpty<TSource>(IEnumerable<TSource>)

傳回指定之序列的項目;如果序列是空的,則傳回單一集合中型別參數的預設值。

DefaultIfEmpty<TSource>(IEnumerable<TSource>, TSource)

傳回指定之序列的項目;如果序列是空的,則傳回單一集合中型別參數的預設值。

Distinct<TSource>(IEnumerable<TSource>)

使用預設的相等比較子來比較值,以便從序列傳回獨特的項目。

Distinct<TSource>(IEnumerable<TSource>, IEqualityComparer<TSource>)

使用指定的 IEqualityComparer<T> 來比較值,以便從序列傳回獨特的項目。

DistinctBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>)

根據指定的索引鍵選取器函式,從序列傳回不同的專案。

DistinctBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>, IEqualityComparer<TKey>)

根據指定的索引鍵選取器函式,並使用指定的比較子比較索引鍵,從序列傳回不同的專案。

ElementAt<TSource>(IEnumerable<TSource>, Index)

傳回位於序列中指定索引處的項目。

ElementAt<TSource>(IEnumerable<TSource>, Int32)

傳回位於序列中指定索引處的項目。

ElementAtOrDefault<TSource>(IEnumerable<TSource>, Index)

傳回位於序列中指定索引處的元素;如果索引超出範圍,則傳回預設值。

ElementAtOrDefault<TSource>(IEnumerable<TSource>, Int32)

傳回位於序列中指定索引處的元素;如果索引超出範圍,則傳回預設值。

Except<TSource>(IEnumerable<TSource>, IEnumerable<TSource>)

使用預設相等比較子來比較值,以便產生兩個序列的差異。

Except<TSource>(IEnumerable<TSource>, IEnumerable<TSource>, IEqualityComparer<TSource>)

使用指定的 IEqualityComparer<T> 來比較值,以便產生兩個序列的差異。

ExceptBy<TSource,TKey>(IEnumerable<TSource>, IEnumerable<TKey>, Func<TSource,TKey>)

根據指定的索引鍵選取器函式,產生兩個序列的集合差異。

ExceptBy<TSource,TKey>(IEnumerable<TSource>, IEnumerable<TKey>, Func<TSource,TKey>, IEqualityComparer<TKey>)

根據指定的索引鍵選取器函式,產生兩個序列的集合差異。

First<TSource>(IEnumerable<TSource>)

傳回序列的第一個項目。

First<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)

傳回序列中符合指定條件的第一個元素。

FirstOrDefault<TSource>(IEnumerable<TSource>)

傳回序列的第一個元素;如果序列中沒有包含任何元素,則傳回預設值。

FirstOrDefault<TSource>(IEnumerable<TSource>, TSource)

傳回序列的第一個專案,如果序列不包含任何專案,則傳回指定的預設值。

FirstOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)

傳回序列中符合條件的第一個元素;如果找不到這類元素,則傳回預設值。

FirstOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>, TSource)

傳回符合條件之序列的第一個專案,如果沒有找到這類專案,則傳回指定的預設值。

GroupBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>)

依據指定的索引鍵選擇器函式來群組序列的項目。

GroupBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>, IEqualityComparer<TKey>)

依據指定的索引鍵選取器函式來群組序列的項目,並使用指定的比較子來比較索引鍵。

GroupBy<TSource,TKey,TElement>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TElement>)

依據指定的索引鍵選取器函式來群組序列的項目,並使用指定的函式來投影每個群組的項目。

GroupBy<TSource,TKey,TElement>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TElement>, IEqualityComparer<TKey>)

依據索引鍵選取器函式來群組序列中的項目。 索引鍵是使用比較子來進行比較,而每個群組的項目都是利用指定的函式進行投影。

GroupBy<TSource,TKey,TResult>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TKey,IEnumerable<TSource>,TResult>)

依據指定的索引鍵選取器函式來群組序列的項目,並從每個群組及其索引鍵建立結果值。

GroupBy<TSource,TKey,TResult>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TKey,IEnumerable<TSource>,TResult>, IEqualityComparer<TKey>)

依據指定的索引鍵選取器函式來群組序列的項目,並從每個群組及其索引鍵建立結果值。 索引鍵是使用指定的比較子來進行比較。

GroupBy<TSource,TKey,TElement,TResult>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TElement>, Func<TKey,IEnumerable<TElement>,TResult>)

依據指定的索引鍵選取器函式來群組序列的項目,並從每個群組及其索引鍵建立結果值。 每個群組的項目都是利用指定的函式進行投影。

GroupBy<TSource,TKey,TElement,TResult>(IEnumerable<TSource>, Func<TSource, TKey>, Func<TSource,TElement>, Func<TKey,IEnumerable<TElement>, TResult>, IEqualityComparer<TKey>)

依據指定的索引鍵選取器函式來群組序列的項目,並從每個群組及其索引鍵建立結果值。 索引鍵值是使用指定的比較子來進行比較,而每個群組的項目則都是利用指定的函式進行投影。

GroupJoin<TOuter,TInner,TKey,TResult>(IEnumerable<TOuter>, IEnumerable<TInner>, Func<TOuter,TKey>, Func<TInner,TKey>, Func<TOuter,IEnumerable<TInner>, TResult>)

根據索引鍵相等與否,將兩個序列的項目相互關聯,並群組產生的結果。 預設的相等比較子是用於比較索引鍵。

GroupJoin<TOuter,TInner,TKey,TResult>(IEnumerable<TOuter>, IEnumerable<TInner>, Func<TOuter,TKey>, Func<TInner,TKey>, Func<TOuter,IEnumerable<TInner>, TResult>, IEqualityComparer<TKey>)

根據索引鍵相等與否,將兩個序列的項目相互關聯,並群組產生的結果。 指定的 IEqualityComparer<T> 是用於比較索引鍵。

Index<TSource>(IEnumerable<TSource>)

為內嵌在值之索引鍵的集合,提供抽象基底類別。

Intersect<TSource>(IEnumerable<TSource>, IEnumerable<TSource>)

使用預設相等比較子來比較值,以便產生兩個序列的交集。

Intersect<TSource>(IEnumerable<TSource>, IEnumerable<TSource>, IEqualityComparer<TSource>)

使用指定的 IEqualityComparer<T> 來比較值,以便產生兩個序列的交集。

IntersectBy<TSource,TKey>(IEnumerable<TSource>, IEnumerable<TKey>, Func<TSource,TKey>)

根據指定的索引鍵選取器函式,產生兩個序列的集合交集。

IntersectBy<TSource,TKey>(IEnumerable<TSource>, IEnumerable<TKey>, Func<TSource,TKey>, IEqualityComparer<TKey>)

根據指定的索引鍵選取器函式,產生兩個序列的集合交集。

Join<TOuter,TInner,TKey,TResult>(IEnumerable<TOuter>, IEnumerable<TInner>, Func<TOuter,TKey>, Func<TInner,TKey>, Func<TOuter,TInner,TResult>)

根據相符索引鍵,將兩個序列的項目相互關聯。 預設的相等比較子是用於比較索引鍵。

Join<TOuter,TInner,TKey,TResult>(IEnumerable<TOuter>, IEnumerable<TInner>, Func<TOuter,TKey>, Func<TInner,TKey>, Func<TOuter,TInner,TResult>, IEqualityComparer<TKey>)

根據相符索引鍵,將兩個序列的項目相互關聯。 指定的 IEqualityComparer<T> 是用於比較索引鍵。

Last<TSource>(IEnumerable<TSource>)

傳回序列的最後一個項目。

Last<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)

傳回序列中符合指定之條件的最後一個元素。

LastOrDefault<TSource>(IEnumerable<TSource>)

傳回序列的最後一個元素;如果序列中沒有包含任何元素,則傳回預設值。

LastOrDefault<TSource>(IEnumerable<TSource>, TSource)

傳回序列的最後一個專案,如果序列不包含任何專案,則傳回指定的預設值。

LastOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)

傳回序列中符合條件的最後一個元素;如果找不到這類元素,則傳回預設值。

LastOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>, TSource)

傳回符合條件之序列的最後一個專案,如果沒有找到這類專案,則傳回指定的預設值。

LongCount<TSource>(IEnumerable<TSource>)

傳回代表序列中項目總數的 Int64

LongCount<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)

傳回 Int64,其代表序列中符合條件的項目數目。

Max<TSource>(IEnumerable<TSource>)

傳回泛型序列中的最大值。

Max<TSource>(IEnumerable<TSource>, IComparer<TSource>)

傳回泛型序列中的最大值。

Max<TSource>(IEnumerable<TSource>, Func<TSource,Decimal>)

在序列的每個項目上叫用轉換函式,並傳回最大的 Decimal 值。

Max<TSource>(IEnumerable<TSource>, Func<TSource,Double>)

在序列的每個項目上叫用轉換函式,並傳回最大的 Double 值。

Max<TSource>(IEnumerable<TSource>, Func<TSource,Int32>)

在序列的每個項目上叫用轉換函式,並傳回最大的 Int32 值。

Max<TSource>(IEnumerable<TSource>, Func<TSource,Int64>)

在序列的每個項目上叫用轉換函式,並傳回最大的 Int64 值。

Max<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Decimal>>)

在序列的每個項目上叫用轉換函式,並傳回最大的可為 Null 之 Decimal 值。

Max<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Double>>)

在序列的每個項目上叫用轉換函式,並傳回最大的可為 Null 之 Double 值。

Max<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Int32>>)

在序列的每個項目上叫用轉換函式,並傳回最大的可為 Null 之 Int32 值。

Max<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Int64>>)

在序列的每個項目上叫用轉換函式,並傳回最大的可為 Null 之 Int64 值。

Max<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Single>>)

在序列的每個項目上叫用轉換函式,並傳回最大的可為 Null 之 Single 值。

Max<TSource>(IEnumerable<TSource>, Func<TSource,Single>)

在序列的每個項目上叫用轉換函式,並傳回最大的 Single 值。

Max<TSource,TResult>(IEnumerable<TSource>, Func<TSource,TResult>)

在泛型序列的每個項目上叫用轉換函式,並傳回最大的結果值。

MaxBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>)

根據指定的索引鍵選取器函式,傳回泛型序列中的最大值。

MaxBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>, IComparer<TKey>)

根據指定的索引鍵選取器函式和索引鍵比較子,傳回泛型序列中的最大值。

Min<TSource>(IEnumerable<TSource>)

傳回泛型序列中的最小值。

Min<TSource>(IEnumerable<TSource>, IComparer<TSource>)

傳回泛型序列中的最小值。

Min<TSource>(IEnumerable<TSource>, Func<TSource,Decimal>)

在序列的每個項目上叫用轉換函式,並傳回最小的 Decimal 值。

Min<TSource>(IEnumerable<TSource>, Func<TSource,Double>)

在序列的每個項目上叫用轉換函式,並傳回最小的 Double 值。

Min<TSource>(IEnumerable<TSource>, Func<TSource,Int32>)

在序列的每個項目上叫用轉換函式,並傳回最小的 Int32 值。

Min<TSource>(IEnumerable<TSource>, Func<TSource,Int64>)

在序列的每個項目上叫用轉換函式,並傳回最小的 Int64 值。

Min<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Decimal>>)

在序列的每個項目上叫用轉換函式,並傳回最小的可為 Null 之 Decimal 值。

Min<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Double>>)

在序列的每個項目上叫用轉換函式,並傳回最小的可為 Null 之 Double 值。

Min<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Int32>>)

在序列的每個項目上叫用轉換函式,並傳回最小的可為 Null 之 Int32 值。

Min<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Int64>>)

在序列的每個項目上叫用轉換函式,並傳回最小的可為 Null 之 Int64 值。

Min<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Single>>)

在序列的每個項目上叫用轉換函式,並傳回最小的可為 Null 之 Single 值。

Min<TSource>(IEnumerable<TSource>, Func<TSource,Single>)

在序列的每個項目上叫用轉換函式,並傳回最小的 Single 值。

Min<TSource,TResult>(IEnumerable<TSource>, Func<TSource,TResult>)

在泛型序列的每個項目上叫用轉換函式,並傳回最小的結果值。

MinBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>)

根據指定的索引鍵選取器函式,傳回泛型序列中的最小值。

MinBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>, IComparer<TKey>)

根據指定的索引鍵選取器函式和索引鍵比較子,傳回泛型序列中的最小值。

OfType<TResult>(IEnumerable)

根據指定的型別來篩選 IEnumerable 的項目。

Order<T>(IEnumerable<T>)

依遞增順序排序序列中的項目。

Order<T>(IEnumerable<T>, IComparer<T>)

依遞增順序排序序列中的項目。

OrderBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>)

依據索引鍵,按遞增順序排序序列中的項目。

OrderBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>, IComparer<TKey>)

使用指定的比較子,依遞增順序排序序列中的項目。

OrderByDescending<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>)

依據索引鍵,按遞減順序排序序列中的項目。

OrderByDescending<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>, IComparer<TKey>)

使用指定的比較子,依遞減順序排序序列中的項目。

OrderDescending<T>(IEnumerable<T>)

依遞減順序排序序列中的項目。

OrderDescending<T>(IEnumerable<T>, IComparer<T>)

依遞減順序排序序列中的項目。

Prepend<TSource>(IEnumerable<TSource>, TSource)

將值新增至序列的開頭。

Reverse<TSource>(IEnumerable<TSource>)

反轉序列中項目的排序方向。

Select<TSource,TResult>(IEnumerable<TSource>, Func<TSource,TResult>)

將序列的每個元素規劃成一個新的表單。

Select<TSource,TResult>(IEnumerable<TSource>, Func<TSource,Int32,TResult>)

透過加入項目的索引,將序列的每個項目投影成新的表單。

SelectMany<TSource,TResult>(IEnumerable<TSource>, Func<TSource,IEnumerable<TResult>>)

將序列的每個項目都投影成 IEnumerable<T>,並將產生的序列簡化成單一序列。

SelectMany<TSource,TResult>(IEnumerable<TSource>, Func<TSource,Int32,IEnumerable<TResult>>)

將序列的每個項目都投影成 IEnumerable<T>,並將產生的序列簡化成單一序列。 各來源項目的索引是在該項目的投影表單中使用。

SelectMany<TSource,TCollection,TResult>(IEnumerable<TSource>, Func<TSource,IEnumerable<TCollection>>, Func<TSource,TCollection,TResult>)

將序列的每個項目投影為 IEnumerable<T>、將產生的序列簡化成單一序列,並對其中的每個項目叫用結果選取器函式。

SelectMany<TSource,TCollection,TResult>(IEnumerable<TSource>, Func<TSource,Int32,IEnumerable<TCollection>>, Func<TSource,TCollection,TResult>)

將序列的每個項目投影為 IEnumerable<T>、將產生的序列簡化成單一序列,並對其中的每個項目叫用結果選取器函式。 各來源項目的索引是在該項目的中繼投影表單中使用。

SequenceEqual<TSource>(IEnumerable<TSource>, IEnumerable<TSource>)

使用項目之型別的預設相等比較子來比較項目,以判斷兩個序列是否相等。

SequenceEqual<TSource>(IEnumerable<TSource>, IEnumerable<TSource>, IEqualityComparer<TSource>)

使用指定的 IEqualityComparer<T> 來比較項目,以判斷兩個序列是否相等。

Single<TSource>(IEnumerable<TSource>)

傳回序列的唯一一個元素,如果序列中不是正好一個元素,則擲回例外狀況。

Single<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)

傳回序列中符合指定之條件的唯一一個元素,如果有一個以上這類元素,則擲回例外狀況。

SingleOrDefault<TSource>(IEnumerable<TSource>)

傳回序列的唯一一個項目,如果序列是空白,則為預設值,如果序列中有一個以上的項目,這個方法就會擲回例外狀況。

SingleOrDefault<TSource>(IEnumerable<TSource>, TSource)

傳回序列的唯一專案;如果序列是空的,則傳回指定的預設值;如果序列中有一個以上的元素,這個方法會擲回例外狀況。

SingleOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)

傳回序列中符合指定之條件的唯一一個元素,如果沒有這類元素,則為預設值,如果有一個以上的元素符合條件,這個方法就會擲回例外狀況。

SingleOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>, TSource)

傳回符合指定條件之序列的唯一專案;如果沒有這類專案存在,則傳回指定的預設值;如果多個元素符合條件,這個方法會擲回例外狀況。

Skip<TSource>(IEnumerable<TSource>, Int32)

略過序列中指定的項目數目,然後傳回其餘項目。

SkipLast<TSource>(IEnumerable<TSource>, Int32)

傳回新的可列舉集合,其包含已省略來源集合最後 count 元素的所有 source 元素。

SkipWhile<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)

只要指定的條件為 true,便略過序列中的項目,然後傳回其餘項目。

SkipWhile<TSource>(IEnumerable<TSource>, Func<TSource,Int32,Boolean>)

只要指定的條件為 true,便略過序列中的項目,然後傳回其餘項目。 項目的索引是用於述詞功能的邏輯中。

Sum<TSource>(IEnumerable<TSource>, Func<TSource,Decimal>)

計算在輸入序列中各項目上叫用轉換函式後所取得之 Decimal 值序列的總和。

Sum<TSource>(IEnumerable<TSource>, Func<TSource,Double>)

計算在輸入序列中各項目上叫用轉換函式後所取得之 Double 值序列的總和。

Sum<TSource>(IEnumerable<TSource>, Func<TSource,Int32>)

計算在輸入序列中各項目上叫用轉換函式後所取得之 Int32 值序列的總和。

Sum<TSource>(IEnumerable<TSource>, Func<TSource,Int64>)

計算在輸入序列中各項目上叫用轉換函式後所取得之 Int64 值序列的總和。

Sum<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Decimal>>)

計算在輸入序列中各項目上叫用轉換函式後所取得可為 Null 之 Decimal 值的總和。

Sum<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Double>>)

計算在輸入序列中各項目上叫用轉換函式後所取得可為 Null 之 Double 值的總和。

Sum<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Int32>>)

計算在輸入序列中各項目上叫用轉換函式後所取得可為 Null 之 Int32 值的總和。

Sum<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Int64>>)

計算在輸入序列中各項目上叫用轉換函式後所取得可為 Null 之 Int64 值的總和。

Sum<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Single>>)

計算在輸入序列中各項目上叫用轉換函式後所取得可為 Null 之 Single 值的總和。

Sum<TSource>(IEnumerable<TSource>, Func<TSource,Single>)

計算在輸入序列中各項目上叫用轉換函式後所取得之 Single 值序列的總和。

Take<TSource>(IEnumerable<TSource>, Int32)

從序列開頭傳回指定的連續項目數目。

Take<TSource>(IEnumerable<TSource>, Range)

從序列傳回指定的連續專案範圍。

TakeLast<TSource>(IEnumerable<TSource>, Int32)

傳回新的可列舉集合,其包含 source 的最後 count 元素。

TakeWhile<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)

只要指定的條件為 true,就會傳回序列中的項目。

TakeWhile<TSource>(IEnumerable<TSource>, Func<TSource,Int32,Boolean>)

只要指定的條件為 true,就會傳回序列中的項目。 項目的索引是用於述詞功能的邏輯中。

ToArray<TSource>(IEnumerable<TSource>)

IEnumerable<T> 建立陣列。

ToDictionary<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>)

根據指定的索引鍵選擇器函式,從 Dictionary<TKey,TValue> 建立 IEnumerable<T>

ToDictionary<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>, IEqualityComparer<TKey>)

根據指定的索引鍵選取器函式和索引鍵比較子,從 Dictionary<TKey,TValue> 建立 IEnumerable<T>

ToDictionary<TSource,TKey,TElement>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TElement>)

根據指定的索引鍵選取器和項目選取器函式,從 Dictionary<TKey,TValue> 建立 IEnumerable<T>

ToDictionary<TSource,TKey,TElement>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TElement>, IEqualityComparer<TKey>)

根據指定的索引鍵選取器函式、比較子和項目選取器函式,從 Dictionary<TKey,TValue> 建立 IEnumerable<T>

ToHashSet<TSource>(IEnumerable<TSource>)

IEnumerable<T> 建立 HashSet<T>

ToHashSet<TSource>(IEnumerable<TSource>, IEqualityComparer<TSource>)

使用比較金鑰的 comparerIEnumerable<T> 建立 HashSet<T>

ToList<TSource>(IEnumerable<TSource>)

IEnumerable<T> 建立 List<T>

ToLookup<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>)

根據指定的索引鍵選擇器函式,從 Lookup<TKey,TElement> 建立 IEnumerable<T>

ToLookup<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>, IEqualityComparer<TKey>)

根據指定的索引鍵選取器函式和索引鍵比較子,從 Lookup<TKey,TElement> 建立 IEnumerable<T>

ToLookup<TSource,TKey,TElement>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TElement>)

根據指定的索引鍵選取器和項目選取器函式,從 Lookup<TKey,TElement> 建立 IEnumerable<T>

ToLookup<TSource,TKey,TElement>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TElement>, IEqualityComparer<TKey>)

根據指定的索引鍵選取器函式、比較子和項目選取器函式,從 Lookup<TKey,TElement> 建立 IEnumerable<T>

TryGetNonEnumeratedCount<TSource>(IEnumerable<TSource>, Int32)

嘗試判斷序列中的元素數目,而不強制列舉。

Union<TSource>(IEnumerable<TSource>, IEnumerable<TSource>)

使用預設相等比較值來比較值,以便產生兩個序列的集合等位。

Union<TSource>(IEnumerable<TSource>, IEnumerable<TSource>, IEqualityComparer<TSource>)

使用指定的 IEqualityComparer<T> 產生兩個序列的集合等位。

UnionBy<TSource,TKey>(IEnumerable<TSource>, IEnumerable<TSource>, Func<TSource,TKey>)

根據指定的索引鍵選取器函式,產生兩個序列的集合聯集。

UnionBy<TSource,TKey>(IEnumerable<TSource>, IEnumerable<TSource>, Func<TSource,TKey>, IEqualityComparer<TKey>)

根據指定的索引鍵選取器函式,產生兩個序列的集合聯集。

Where<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)

根據述詞來篩選值序列。

Where<TSource>(IEnumerable<TSource>, Func<TSource,Int32,Boolean>)

根據述詞來篩選值序列。 述詞函式的邏輯中使用各項目的索引。

Zip<TFirst,TSecond>(IEnumerable<TFirst>, IEnumerable<TSecond>)

從兩個指定序列中的元素產生一系列元組。

Zip<TFirst,TSecond,TThird>(IEnumerable<TFirst>, IEnumerable<TSecond>, IEnumerable<TThird>)

產生具有來自三個指定序列之元素的元組序列。

Zip<TFirst,TSecond,TResult>(IEnumerable<TFirst>, IEnumerable<TSecond>, Func<TFirst,TSecond,TResult>)

將指定的函式套用至兩個序列的對應項目,產生結果的序列。

AsParallel(IEnumerable)

啟用查詢的平行化作業。

AsParallel<TSource>(IEnumerable<TSource>)

啟用查詢的平行化作業。

AsQueryable(IEnumerable)

IEnumerable 轉換成 IQueryable

AsQueryable<TElement>(IEnumerable<TElement>)

將泛型 IEnumerable<T> 轉換成泛型 IQueryable<T>

Ancestors<T>(IEnumerable<T>)

傳回包含來源集合中每個節點祖系的項目集合。

Ancestors<T>(IEnumerable<T>, XName)

傳回包含來源集合中每個節點祖系的已篩選項目集合。 集合中只會包含具有相符之 XName 的項目。

DescendantNodes<T>(IEnumerable<T>)

傳回來源集合中每個文件和項目之子代節點的集合。

Descendants<T>(IEnumerable<T>)

傳回包含來源集合中每個項目和文件之子代項目的項目集合。

Descendants<T>(IEnumerable<T>, XName)

傳回已篩選的項目集合,其中包含來源集合中每個項目和文件的子代項目。 集合中只會包含具有相符之 XName 的項目。

Elements<T>(IEnumerable<T>)

傳回來源集合中每個項目和文件的子項目集合。

Elements<T>(IEnumerable<T>, XName)

傳回來源集合中每個項目和文件的已篩選子項目集合。 集合中只會包含具有相符之 XName 的項目。

InDocumentOrder<T>(IEnumerable<T>)

傳回包含來源集合中所有節點的節點集合,依據文件順序來排序。

Nodes<T>(IEnumerable<T>)

傳回來源集合中每個文件和項目的子節點集合。

Remove<T>(IEnumerable<T>)

在來源集合中,從每一個節點的父節點移除這些節點。

適用於

另請參閱