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

В следующем примере кода показано, как переопределить защищенные InsertItemметоды , RemoveItem, ClearItemsи SetItem , чтобы обеспечить настраиваемое поведение для Addметодов , Removeи Clear и для задания свойства по умолчанию Item[] (индексатор в C#). Пользовательское поведение, предоставляемое в этом примере, представляет собой событие уведомления с именем 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> (KeyedCollection(Of String, String) в Visual Basic), может быть "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, содержащий копии объектов DataRow при заданном входном объекте IEnumerable<T> и универсальном параметре T, равном DataRow.

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

Копирует объекты DataRow в указанный объект DataTable с заданным входным объектом IEnumerable<T>, где универсальный параметр T имеет значение DataRow.

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

Копирует объекты DataRow в указанный объект DataTable с заданным входным объектом IEnumerable<T>, где универсальный параметр 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>>)

Вычисляет среднее для последовательности значений Decimal обнуляемого типа, получаемой в результате применения функции преобразования к каждому элементу входной последовательности.

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

Вычисляет среднее для последовательности значений Double обнуляемого типа, получаемой в результате применения функции преобразования к каждому элементу входной последовательности.

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

Вычисляет среднее для последовательности значений Int32 обнуляемого типа, получаемой в результате применения функции преобразования к каждому элементу входной последовательности.

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

Вычисляет среднее для последовательности значений Int64 обнуляемого типа, получаемой в результате применения функции преобразования к каждому элементу входной последовательности.

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

Вычисляет среднее для последовательности значений 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)

Определяет, содержится ли указанный элемент в последовательности, используя компаратор проверки на равенство по умолчанию.

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>>)

Вызывает функцию преобразования для каждого элемента последовательности и возвращает максимальное значение Decimal обнуляемого типа.

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

Вызывает функцию преобразования для каждого элемента последовательности и возвращает максимальное значение Double обнуляемого типа.

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

Вызывает функцию преобразования для каждого элемента последовательности и возвращает максимальное значение Int32 обнуляемого типа.

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

Вызывает функцию преобразования для каждого элемента последовательности и возвращает максимальное значение Int64 обнуляемого типа.

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

Вызывает функцию преобразования для каждого элемента последовательности и возвращает максимальное значение 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>>)

Вызывает функцию преобразования для каждого элемента последовательности и возвращает минимальное значение Decimal обнуляемого типа.

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

Вызывает функцию преобразования для каждого элемента последовательности и возвращает минимальное значение Double обнуляемого типа.

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

Вызывает функцию преобразования для каждого элемента последовательности и возвращает минимальное значение Int32 обнуляемого типа.

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

Вызывает функцию преобразования для каждого элемента последовательности и возвращает минимальное значение Int64 обнуляемого типа.

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

Вызывает функцию преобразования для каждого элемента последовательности и возвращает минимальное значение 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>)

Возвращает единственный элемент последовательности и генерирует исключение, если число элементов последовательности отлично от 1.

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)

Возвращает новую перечислимую коллекцию, содержащую элементы из source с исключенными count элементами из конца исходной коллекции.

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

Пропускает элементы в последовательности, пока они удовлетворяют заданному условию, и затем возвращает оставшиеся элементы.

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

Пропускает элементы в последовательности, пока они удовлетворяют заданному условию, и затем возвращает оставшиеся элементы. Индекс элемента используется в логике функции предиката.

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>>)

Вычисляет сумму последовательности значений Decimal обнуляемого типа, получаемой в результате применения функции преобразования к каждому элементу входной последовательности.

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

Вычисляет сумму последовательности значений Double обнуляемого типа, получаемой в результате применения функции преобразования к каждому элементу входной последовательности.

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

Вычисляет сумму последовательности значений Int32 обнуляемого типа, получаемой в результате применения функции преобразования к каждому элементу входной последовательности.

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

Вычисляет сумму последовательности значений Int64 обнуляемого типа, получаемой в результате применения функции преобразования к каждому элементу входной последовательности.

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

Вычисляет сумму последовательности значений Single обнуляемого типа, получаемой в результате применения функции преобразования к каждому элементу входной последовательности.

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

Вычисляет сумму последовательности значений типа Single, получаемой в результате применения функции преобразования к каждому элементу входной последовательности.

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

Возвращает указанное число подряд идущих элементов с начала последовательности.

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

Возвращает указанный диапазон смежных элементов из последовательности.

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

Возвращает новую перечислимую коллекцию, содержащую последние count элементов из source.

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

Возвращает цепочку элементов последовательности, удовлетворяющих указанному условию.

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

Возвращает цепочку элементов последовательности, удовлетворяющих указанному условию. Индекс элемента используется в логике функции предиката.

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>)

Создает HashSet<T> из IEnumerable<T>.

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

Создает HashSet<T> из IEnumerable<T> с использованием comparer для сравнения ключей.

ToList<TSource>(IEnumerable<TSource>)

Создает List<T> из IEnumerable<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>)

Удаление каждого узла в исходной коллекции из родительского узла.

Применяется к

См. также раздел