KeyedCollection<TKey,TItem> Class

Definition

Proporciona la clase base abstracta para una colección cuyas claves están incrustadas en los valores.Provides the abstract base class for a collection whose keys are embedded in the values.

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>
Public MustInherit Class KeyedCollection(Of TKey, TItem)
Inherits Collection(Of TItem)

Type Parameters

TKey

Tipo de claves de la colección.The type of keys in the collection.

TItem

Tipo de elementos de la colección.The type of items in the collection.

Inheritance
Collection<TItem>
KeyedCollection<TKey,TItem>
Derived
Attributes

Examples

Esta sección contiene dos ejemplos de código.This section contains two code examples. En el primer ejemplo se muestra el código mínimo necesario para derivar de KeyedCollection<TKey,TItem>y se muestran muchos de los métodos heredados.The first example shows the minimum code required to derive from KeyedCollection<TKey,TItem>, and demonstrates many of the inherited methods. En el segundo ejemplo se muestra cómo invalidar los métodos protegidos de KeyedCollection<TKey,TItem> para proporcionar un comportamiento personalizado.The second example shows how to override the protected methods of KeyedCollection<TKey,TItem> to provide custom behavior.

Ejemplo 1Example 1

En este ejemplo de código se muestra el código mínimo necesario para derivar una clase de colección de KeyedCollection<TKey,TItem>: invalidar el método GetKeyForItem y proporcionar un constructor público que delegue en un constructor de clase base.This code example shows the minimum code necessary to derive a collection class from KeyedCollection<TKey,TItem>: overriding the GetKeyForItem method and providing a public constructor that delegates to a base class constructor. En el ejemplo de código también se muestran muchas de las propiedades y métodos heredados de las clases KeyedCollection<TKey,TItem> y Collection<T>.The code example also demonstrates many of the properties and methods inherited from KeyedCollection<TKey,TItem> and Collection<T> classes.

La clase SimpleOrder es una lista de solicitudes muy simple que contiene OrderItem objetos, cada uno de los cuales representa un elemento de línea en el orden.The SimpleOrder class is a very simple requisition list that contains OrderItem objects, each of which represents a line item in the order. La clave de OrderItem es inmutable, una consideración importante para las clases que derivan de KeyedCollection<TKey,TItem>.The key of OrderItem is immutable, an important consideration for classes that derive from KeyedCollection<TKey,TItem>. Para obtener un ejemplo de código que usa claves mutables, vea ChangeItemKey.For a code example that uses mutable keys, see 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

Ejemplo 2Example 2

En el ejemplo de código siguiente se muestra cómo invalidar los métodos protegidos InsertItem, RemoveItem, ClearItemsy SetItem para proporcionar un comportamiento personalizado para los métodos Add, Removey Clear, y para establecer la propiedad Item[] predeterminada (el indizador C#en).The following code example shows how to override the protected InsertItem, RemoveItem, ClearItems, and SetItem methods, to provide custom behavior for the Add, Remove, and Clear methods, and for setting the default Item[] property (the indexer in C#). El comportamiento personalizado proporcionado en este ejemplo es un evento de notificación denominado Changed, que se genera al final de cada uno de los métodos invalidados.The custom behavior provided in this example is a notification event named Changed, which is raised at the end of each of the overridden methods.

En el ejemplo de código se crea la clase SimpleOrder, que se deriva de KeyedCollection<TKey,TItem> y representa un formulario de pedido simple.The code example creates the SimpleOrder class, which derives from KeyedCollection<TKey,TItem> and represents a simple order form. El formulario de pedido contiene OrderItem objetos que representan los elementos solicitados.The order form contains OrderItem objects representing items ordered. En el ejemplo de código también se crea una clase SimpleOrderChangedEventArgs que contiene la información del evento y una enumeración para identificar el tipo de cambio.The code example also creates a SimpleOrderChangedEventArgs class to contain the event information, and an enumeration to identify the type of change.

En el ejemplo de código se muestra el comportamiento personalizado llamando a las propiedades y métodos de la clase derivada, en el método Main de la clase Demo.The code example demonstrates the custom behavior by calling the properties and methods of the derived class, in the Main method of the Demo class.

En este ejemplo de código se usan objetos con claves inmutables.This code example uses objects with immutable keys. Para obtener un ejemplo de código que usa claves mutables, vea ChangeItemKey.For a code example that uses mutable keys, see 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.

Remarks

La clase KeyedCollection<TKey,TItem> proporciona tanto la recuperación indizada de O (1) como la recuperación con clave que se aproxima a O (1).The KeyedCollection<TKey,TItem> class provides both O(1) indexed retrieval and keyed retrieval that approaches O(1). Es un tipo abstracto, o más preciso, un conjunto infinito de tipos abstractos, ya que cada uno de sus tipos genéricos construidos es una clase base abstracta.It is an abstract type, or more accurately an infinite set of abstract types, because each of its constructed generic types is an abstract base class. Para usar KeyedCollection<TKey,TItem>, derive el tipo de colección del tipo construido adecuado.To use KeyedCollection<TKey,TItem>, derive your collection type from the appropriate constructed type.

La clase KeyedCollection<TKey,TItem> es un híbrido entre una colección basada en la interfaz genérica IList<T> y una colección basada en la interfaz genérica IDictionary<TKey,TValue>.The KeyedCollection<TKey,TItem> class is a hybrid between a collection based on the IList<T> generic interface and a collection based on the IDictionary<TKey,TValue> generic interface. Al igual que las colecciones basadas en la interfaz genérica de IList<T>, KeyedCollection<TKey,TItem> es una lista indizada de elementos.Like collections based on the IList<T> generic interface, KeyedCollection<TKey,TItem> is an indexed list of items. Al igual que las colecciones basadas en la interfaz genérica IDictionary<TKey,TValue>, KeyedCollection<TKey,TItem> tiene una clave asociada a cada elemento.Like collections based on the IDictionary<TKey,TValue> generic interface, KeyedCollection<TKey,TItem> has a key associated with each element.

A diferencia de los diccionarios, un elemento de KeyedCollection<TKey,TItem> no es un par clave-valor. en su lugar, el elemento completo es el valor y la clave se incrusta dentro del valor.Unlike dictionaries, an element of KeyedCollection<TKey,TItem> is not a key/value pair; instead, the entire element is the value and the key is embedded within the value. Por ejemplo, un elemento de una colección derivado de KeyedCollection\<String,String> (KeyedCollection(Of String, String) en Visual Basic) podría ser "John Doe Jr".For example, an element of a collection derived from KeyedCollection\<String,String> (KeyedCollection(Of String, String) in Visual Basic) might be "John Doe Jr." donde el valor es "John Doe Jr".where the value is "John Doe Jr." y la clave es "DOE"; o bien, una colección de registros de empleados que contienen claves de enteros podría derivarse de KeyedCollection\<int,Employee>.and the key is "Doe"; or a collection of employee records containing integer keys could be derived from KeyedCollection\<int,Employee>. El método Abstract GetKeyForItem extrae la clave del elemento.The abstract GetKeyForItem method extracts the key from the element.

De forma predeterminada, la KeyedCollection<TKey,TItem> incluye un diccionario de búsqueda que se puede obtener con la propiedad Dictionary.By default, the KeyedCollection<TKey,TItem> includes a lookup dictionary that you can obtain with the Dictionary property. Cuando se agrega un elemento al KeyedCollection<TKey,TItem>, la clave del elemento se extrae una vez y se guarda en el Diccionario de búsqueda para agilizar las búsquedas.When an item is added to the KeyedCollection<TKey,TItem>, the item's key is extracted once and saved in the lookup dictionary for faster searches. Este comportamiento se invalida especificando un umbral de creación de diccionario al crear el KeyedCollection<TKey,TItem>.This behavior is overridden by specifying a dictionary creation threshold when you create the KeyedCollection<TKey,TItem>. El Diccionario de búsqueda se crea la primera vez que el número de elementos supera ese umbral.The lookup dictionary is created the first time the number of elements exceeds that threshold. Si especifica-1 como umbral, el Diccionario de búsqueda nunca se crea.If you specify -1 as the threshold, the lookup dictionary is never created.

Note

Cuando se usa el Diccionario de búsqueda interno, contiene referencias a todos los elementos de la colección si TItem es un tipo de referencia, o copia de todos los elementos de la colección si TItem es un tipo de valor.When the internal lookup dictionary is used, it contains references to all the items in the collection if TItem is a reference type, or copies of all the items in the collection if TItem is a value type. Por lo tanto, es posible que el uso del Diccionario de búsqueda no sea adecuado si TItem es un tipo de valor.Thus, using the lookup dictionary may not be appropriate if TItem is a value type.

Puede tener acceso a un elemento por su índice o clave mediante la propiedad Item[].You can access an item by its index or key by using the Item[] property. Puede agregar elementos sin una clave, pero posteriormente solo se puede tener acceso a estos elementos mediante el índice.You can add items without a key, but these items can subsequently be accessed only by index.

Constructors

KeyedCollection<TKey,TItem>()

Inicializa una nueva instancia de la clase KeyedCollection<TKey,TItem> que utiliza el comparador de igualdad predeterminado.Initializes a new instance of the KeyedCollection<TKey,TItem> class that uses the default equality comparer.

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

Inicializa una nueva instancia de la clase KeyedCollection<TKey,TItem> que utiliza el comparador de igualdad especificado.Initializes a new instance of the KeyedCollection<TKey,TItem> class that uses the specified equality comparer.

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

Inicializa una nueva instancia de la clase KeyedCollection<TKey,TItem> que utiliza el comparador de igualdad especificado y crea un diccionario de búsqueda cuando se supera el umbral especificado.Initializes a new instance of the KeyedCollection<TKey,TItem> class that uses the specified equality comparer and creates a lookup dictionary when the specified threshold is exceeded.

Properties

Comparer

Obtiene el comparador de igualdad genérico que se utiliza para determinar la igualdad de claves en la colección.Gets the generic equality comparer that is used to determine equality of keys in the collection.

Count

Obtiene el número de elementos contenido realmente en Collection<T>.Gets the number of elements actually contained in the Collection<T>.

(Inherited from Collection<T>)
Dictionary

Obtiene el diccionario de búsqueda de KeyedCollection<TKey,TItem>.Gets the lookup dictionary of the KeyedCollection<TKey,TItem>.

Item[Int32]

Obtiene o establece el elemento en el índice especificado.Gets or sets the element at the specified index.

(Inherited from Collection<T>)
Item[TKey]

Obtiene el elemento con la clave especificada.Gets the element with the specified key.

Items

Obtiene un contenedor de IList<T> para la colección Collection<T>.Gets a IList<T> wrapper around the Collection<T>.

(Inherited from Collection<T>)

Methods

Add(T)

Agrega un objeto al final de la colección Collection<T>.Adds an object to the end of the Collection<T>.

(Inherited from Collection<T>)
ChangeItemKey(TItem, TKey)

Cambia la clave asociada al elemento especificado en el diccionario de búsqueda.Changes the key associated with the specified element in the lookup dictionary.

Clear()

Quita todos los elementos de Collection<T>.Removes all elements from the Collection<T>.

(Inherited from Collection<T>)
ClearItems()

Quita todos los elementos de KeyedCollection<TKey,TItem>.Removes all elements from the KeyedCollection<TKey,TItem>.

Contains(TKey)

Determina si la colección contiene un elemento con la clave especificada.Determines whether the collection contains an element with the specified key.

CopyTo(T[], Int32)

Copia la totalidad de Collection<T> en una matriz Array unidimensional compatible, comenzando en el índice especificado de la matriz de destino.Copies the entire Collection<T> to a compatible one-dimensional Array, starting at the specified index of the target array.

(Inherited from Collection<T>)
Equals(Object)

Determina si el objeto especificado es igual al objeto actual.Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetEnumerator()

Devuelve un enumerador que recorre en iteración la colección Collection<T>.Returns an enumerator that iterates through the Collection<T>.

(Inherited from Collection<T>)
GetHashCode()

Sirve como la función hash predeterminada.Serves as the default hash function.

(Inherited from Object)
GetKeyForItem(TItem)

Cuando se implementa en una clase derivada, extrae la clave del elemento especificado.When implemented in a derived class, extracts the key from the specified element.

GetType()

Obtiene el Type de la instancia actual.Gets the Type of the current instance.

(Inherited from Object)
IndexOf(T)

Busca el objeto especificado y devuelve el índice de base cero de la primera aparición en todo el Collection<T>.Searches for the specified object and returns the zero-based index of the first occurrence within the entire Collection<T>.

(Inherited from Collection<T>)
Insert(Int32, T)

Inserta un elemento en Collection<T> en el índice especificado.Inserts an element into the Collection<T> at the specified index.

(Inherited from Collection<T>)
InsertItem(Int32, T)

Inserta un elemento en Collection<T> en el índice especificado.Inserts an element into the Collection<T> at the specified index.

(Inherited from Collection<T>)
InsertItem(Int32, TItem)

Inserta un elemento en KeyedCollection<TKey,TItem> en el índice especificado.Inserts an element into the KeyedCollection<TKey,TItem> at the specified index.

MemberwiseClone()

Crea una copia superficial del Object actual.Creates a shallow copy of the current Object.

(Inherited from Object)
Remove(TKey)

Quita el elemento con la clave especificada de KeyedCollection<TKey,TItem>.Removes the element with the specified key from the KeyedCollection<TKey,TItem>.

RemoveAt(Int32)

Quita el elemento situado en el índice especificado de Collection<T>.Removes the element at the specified index of the Collection<T>.

(Inherited from Collection<T>)
RemoveItem(Int32)

Quita el elemento situado en el índice especificado de KeyedCollection<TKey,TItem>.Removes the element at the specified index of the KeyedCollection<TKey,TItem>.

SetItem(Int32, T)

Reemplaza el elemento que se encuentra en el índice especificado.Replaces the element at the specified index.

(Inherited from Collection<T>)
SetItem(Int32, TItem)

Reemplaza el elemento situado en el índice determinado con el elemento especificado.Replaces the item at the specified index with the specified item.

ToString()

Devuelve una cadena que representa el objeto actual.Returns a string that represents the current object.

(Inherited from Object)
TryGetValue(TKey, TItem)

Intenta obtener un elemento de la colección mediante la clave especificada.Tries to get an item from the collection using the specified key.

Explicit Interface Implementations

ICollection.CopyTo(Array, Int32)

Copia los elementos de ICollection en Array, empezando por un índice determinado de Array.Copies the elements of the ICollection to an Array, starting at a particular Array index.

(Inherited from Collection<T>)
ICollection.IsSynchronized

Obtiene un valor que indica si se sincroniza (seguro para subprocesos) el acceso a ICollection.Gets a value indicating whether access to the ICollection is synchronized (thread safe).

(Inherited from Collection<T>)
ICollection.SyncRoot

Obtiene un objeto que se puede usar para sincronizar el acceso a la clase ICollection.Gets an object that can be used to synchronize access to the ICollection.

(Inherited from Collection<T>)
ICollection<T>.IsReadOnly

Obtiene un valor que indica si la clase ICollection<T> es de solo lectura.Gets a value indicating whether the ICollection<T> is read-only.

(Inherited from Collection<T>)
IEnumerable.GetEnumerator()

Devuelve un enumerador que itera una colección.Returns an enumerator that iterates through a collection.

(Inherited from Collection<T>)
IList.Add(Object)

Agrega un elemento a IList.Adds an item to the IList.

(Inherited from Collection<T>)
IList.Contains(Object)

Determina si IList contiene un valor concreto.Determines whether the IList contains a specific value.

(Inherited from Collection<T>)
IList.IndexOf(Object)

Determina el índice de un elemento específico de IList.Determines the index of a specific item in the IList.

(Inherited from Collection<T>)
IList.Insert(Int32, Object)

Inserta un elemento en la interfaz IList, en el índice especificado.Inserts an item into the IList at the specified index.

(Inherited from Collection<T>)
IList.IsFixedSize

Obtiene un valor que indica si la colección IList tiene un tamaño fijo.Gets a value indicating whether the IList has a fixed size.

(Inherited from Collection<T>)
IList.IsReadOnly

Obtiene un valor que indica si la clase IList es de solo lectura.Gets a value indicating whether the IList is read-only.

(Inherited from Collection<T>)
IList.Item[Int32]

Obtiene o establece el elemento en el índice especificado.Gets or sets the element at the specified index.

(Inherited from Collection<T>)
IList.Remove(Object)

Quita de IList la primera aparición de un objeto concreto.Removes the first occurrence of a specific object from the IList.

(Inherited from Collection<T>)

Extension Methods

ToImmutableArray<TSource>(IEnumerable<TSource>)

Crea una matriz inmutable a partir de la colección especificada.Creates an immutable array from the specified collection.

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

Crea un diccionario inmutable de una colección de elementos existente, aplicando una función de transformación en las claves de origen.Constructs an immutable dictionary from an existing collection of elements, applying a transformation function to the source keys.

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

Crea un diccionario inmutable basado en alguna transformación de una secuencia.Constructs an immutable dictionary based on some transformation of a sequence.

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

Enumera y transforma una secuencia y genera un diccionario inmutable de su contenido.Enumerates and transforms a sequence, and produces an immutable dictionary of its contents.

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

Enumera y transforma una secuencia y genera un diccionario inmutable de su contenido mediante el comparador de claves especificado.Enumerates and transforms a sequence, and produces an immutable dictionary of its contents by using the specified key comparer.

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

Enumera y transforma una secuencia y genera un diccionario inmutable de su contenido mediante el comparador de claves y valores especificado.Enumerates and transforms a sequence, and produces an immutable dictionary of its contents by using the specified key and value comparers.

ToImmutableHashSet<TSource>(IEnumerable<TSource>)

Enumera una secuencia y genera un conjunto hash inmutable de su contenido.Enumerates a sequence and produces an immutable hash set of its contents.

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

Enumera una secuencia, genera un conjunto hash inmutable de su contenido y usa el comparador de igualdad especificado para este tipo de conjunto.Enumerates a sequence, produces an immutable hash set of its contents, and uses the specified equality comparer for the set type.

ToImmutableList<TSource>(IEnumerable<TSource>)

Enumera una secuencia y genera una lista inmutable de su contenido.Enumerates a sequence and produces an immutable list of its contents.

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

Enumera y transforma una secuencia y genera un diccionario ordenado inmutable de su contenido.Enumerates and transforms a sequence, and produces an immutable sorted dictionary of its contents.

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

Enumera y transforma una secuencia y genera un diccionario ordenado inmutable de su contenido mediante el comparador de claves especificado.Enumerates and transforms a sequence, and produces an immutable sorted dictionary of its contents by using the specified key comparer.

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

Enumera y transforma una secuencia y genera un diccionario ordenador inmutable de su contenido mediante el comparador de claves y valores especificado.Enumerates and transforms a sequence, and produces an immutable sorted dictionary of its contents by using the specified key and value comparers.

ToImmutableSortedSet<TSource>(IEnumerable<TSource>)

Enumera una secuencia y genera un conjunto ordenado inmutable de su contenido.Enumerates a sequence and produces an immutable sorted set of its contents.

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

Enumera una secuencia, genera un conjunto ordenado inmutable de su contenido y usa el comparador especificado.Enumerates a sequence, produces an immutable sorted set of its contents, and uses the specified comparer.

CopyToDataTable<T>(IEnumerable<T>)

Devuelve un objeto DataTable que contiene copias de los objetos DataRow, dado un objeto IEnumerable<T> de entrada donde el parámetro T genérico es DataRow.Returns a DataTable that contains copies of the DataRow objects, given an input IEnumerable<T> object where the generic parameter T is DataRow.

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

Copia objetos DataRow en el objeto DataTable especificado, dado un objeto IEnumerable<T> de entrada donde el parámetro T genérico es DataRow.Copies DataRow objects to the specified DataTable, given an input IEnumerable<T> object where the generic parameter T is DataRow.

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

Copia objetos DataRow en el objeto DataTable especificado, dado un objeto IEnumerable<T> de entrada donde el parámetro T genérico es DataRow.Copies DataRow objects to the specified DataTable, given an input IEnumerable<T> object where the generic parameter T is DataRow.

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

Aplica una función de acumulador a una secuencia.Applies an accumulator function over a sequence.

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

Aplica una función de acumulador a una secuencia.Applies an accumulator function over a sequence. El valor de inicialización especificado se utiliza como valor de inicio del acumulador.The specified seed value is used as the initial accumulator value.

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

Aplica una función de acumulador a una secuencia.Applies an accumulator function over a sequence. El valor de inicialización especificado se utiliza como valor inicial del acumulador y la función especificada se utiliza para seleccionar el valor resultante.The specified seed value is used as the initial accumulator value, and the specified function is used to select the result value.

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

Determina si todos los elementos de una secuencia satisfacen una condición.Determines whether all elements of a sequence satisfy a condition.

Any<TSource>(IEnumerable<TSource>)

Determina si una secuencia contiene elementos.Determines whether a sequence contains any elements.

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

Determina si algún elemento de una secuencia satisface una condición.Determines whether any element of a sequence satisfies a condition.

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

Anexa un valor al final de la secuencia.Appends a value to the end of the sequence.

AsEnumerable<TSource>(IEnumerable<TSource>)

Devuelve la entrada con tipo como IEnumerable<T>.Returns the input typed as IEnumerable<T>.

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

Calcula el promedio de una secuencia de valores Decimal que se obtiene al invocar una función de transformación en cada elemento de la secuencia de entrada.Computes the average of a sequence of Decimal values that are obtained by invoking a transform function on each element of the input sequence.

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

Calcula el promedio de una secuencia de valores Double que se obtiene al invocar una función de transformación en cada elemento de la secuencia de entrada.Computes the average of a sequence of Double values that are obtained by invoking a transform function on each element of the input sequence.

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

Calcula el promedio de una secuencia de valores Int32 que se obtiene al invocar una función de transformación en cada elemento de la secuencia de entrada.Computes the average of a sequence of Int32 values that are obtained by invoking a transform function on each element of the input sequence.

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

Calcula el promedio de una secuencia de valores Int64 que se obtiene al invocar una función de transformación en cada elemento de la secuencia de entrada.Computes the average of a sequence of Int64 values that are obtained by invoking a transform function on each element of the input sequence.

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

Calcula el promedio de una secuencia de valores Decimal que aceptan valores NULL que se obtiene al invocar una función de transformación en cada elemento de la secuencia de entrada.Computes the average of a sequence of nullable Decimal values that are obtained by invoking a transform function on each element of the input sequence.

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

Calcula el promedio de una secuencia de valores Double que aceptan valores NULL que se obtiene al invocar una función de transformación en cada elemento de la secuencia de entrada.Computes the average of a sequence of nullable Double values that are obtained by invoking a transform function on each element of the input sequence.

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

Calcula el promedio de una secuencia de valores Int32 que aceptan valores NULL que se obtiene al invocar una función de transformación en cada elemento de la secuencia de entrada.Computes the average of a sequence of nullable Int32 values that are obtained by invoking a transform function on each element of the input sequence.

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

Calcula el promedio de una secuencia de valores Int64 que aceptan valores NULL que se obtiene al invocar una función de transformación en cada elemento de la secuencia de entrada.Computes the average of a sequence of nullable Int64 values that are obtained by invoking a transform function on each element of the input sequence.

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

Calcula el promedio de una secuencia de valores Single que aceptan valores NULL que se obtiene al invocar una función de transformación en cada elemento de la secuencia de entrada.Computes the average of a sequence of nullable Single values that are obtained by invoking a transform function on each element of the input sequence.

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

Calcula el promedio de una secuencia de valores Single que se obtiene al invocar una función de transformación en cada elemento de la secuencia de entrada.Computes the average of a sequence of Single values that are obtained by invoking a transform function on each element of the input sequence.

Cast<TResult>(IEnumerable)

Convierte los elementos de IEnumerable en el tipo especificado.Casts the elements of an IEnumerable to the specified type.

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

Concatena dos secuencias.Concatenates two sequences.

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

Determina si una secuencia contiene un elemento especificado mediante el comparador de igualdad predeterminado.Determines whether a sequence contains a specified element by using the default equality comparer.

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

Determina si una secuencia contiene un elemento especificado utilizando un objeto IEqualityComparer<T> determinado.Determines whether a sequence contains a specified element by using a specified IEqualityComparer<T>.

Count<TSource>(IEnumerable<TSource>)

Devuelve el número de elementos de una secuencia.Returns the number of elements in a sequence.

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

Devuelve un número que representa cuántos elementos de la secuencia especificada satisfacen una condición.Returns a number that represents how many elements in the specified sequence satisfy a condition.

DefaultIfEmpty<TSource>(IEnumerable<TSource>)

Devuelve los elementos de la secuencia especificada o el valor predeterminado del parámetro de tipo en una colección singleton si la secuencia está vacía.Returns the elements of the specified sequence or the type parameter's default value in a singleton collection if the sequence is empty.

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

Devuelve los elementos de la secuencia especificada o el valor especificado en una colección singleton si la secuencia está vacía.Returns the elements of the specified sequence or the specified value in a singleton collection if the sequence is empty.

Distinct<TSource>(IEnumerable<TSource>)

Devuelve diversos elementos de una secuencia utilizando el comparador de igualdad predeterminado para comparar los valores.Returns distinct elements from a sequence by using the default equality comparer to compare values.

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

Devuelve diversos elementos de una secuencia utilizando un objeto IEqualityComparer<T> especificado para comparar los valores.Returns distinct elements from a sequence by using a specified IEqualityComparer<T> to compare values.

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

Devuelve el elemento situado en un índice especificado de una secuencia.Returns the element at a specified index in a sequence.

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

Devuelve el elemento situado en un índice especificado de una secuencia o un valor predeterminado si el índice está fuera del intervalo.Returns the element at a specified index in a sequence or a default value if the index is out of range.

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

Proporciona la diferencia de conjuntos de dos secuencias utilizando el comparador de igualdad predeterminado para comparar los valores.Produces the set difference of two sequences by using the default equality comparer to compare values.

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

Proporciona la diferencia de conjuntos de dos secuencias utilizando el objeto IEqualityComparer<T> especificado para comparar los valores.Produces the set difference of two sequences by using the specified IEqualityComparer<T> to compare values.

First<TSource>(IEnumerable<TSource>)

Devuelve el primer elemento de una secuencia.Returns the first element of a sequence.

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

Devuelve el primer elemento de una secuencia que satisface una condición especificada.Returns the first element in a sequence that satisfies a specified condition.

FirstOrDefault<TSource>(IEnumerable<TSource>)

Devuelve el primer elemento de una secuencia o un valor predeterminado si la secuencia no contiene elementos.Returns the first element of a sequence, or a default value if the sequence contains no elements.

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

Devuelve el primer elemento de la secuencia que satisface una condición o un valor predeterminado si no se encuentra dicho elemento.Returns the first element of the sequence that satisfies a condition or a default value if no such element is found.

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

Agrupa los elementos de una secuencia según una función del selector de claves especificada.Groups the elements of a sequence according to a specified key selector function.

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

Agrupa los elementos de una secuencia según una función del selector de claves especificada y compara las claves utilizando un comparador especificado.Groups the elements of a sequence according to a specified key selector function and compares the keys by using a specified comparer.

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

Agrupa los elementos de una secuencia según una función del selector de claves especificada y proyecta los elementos de cada grupo utilizando una función determinada.Groups the elements of a sequence according to a specified key selector function and projects the elements for each group by using a specified function.

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

Agrupa los elementos de una secuencia conforme a una función del selector de claves.Groups the elements of a sequence according to a key selector function. Las claves se comparan utilizando un comparador y los elementos de cada grupo se proyectan utilizando una función especificada.The keys are compared by using a comparer and each group's elements are projected by using a specified function.

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

Agrupa los elementos de una secuencia según una función del selector de claves especificada y crea un valor de resultado a partir de cada grupo y su clave.Groups the elements of a sequence according to a specified key selector function and creates a result value from each group and its key.

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

Agrupa los elementos de una secuencia según una función del selector de claves especificada y crea un valor de resultado a partir de cada grupo y su clave.Groups the elements of a sequence according to a specified key selector function and creates a result value from each group and its key. Las claves se comparan utilizando un comparador especificado.The keys are compared by using a specified comparer.

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

Agrupa los elementos de una secuencia según una función del selector de claves especificada y crea un valor de resultado a partir de cada grupo y su clave.Groups the elements of a sequence according to a specified key selector function and creates a result value from each group and its key. Los elementos de cada grupo se proyectan utilizando una función determinada.The elements of each group are projected by using a specified function.

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

Agrupa los elementos de una secuencia según una función del selector de claves especificada y crea un valor de resultado a partir de cada grupo y su clave.Groups the elements of a sequence according to a specified key selector function and creates a result value from each group and its key. Los valores de las claves se comparan utilizando un comparador especificado y los elementos de cada grupo se proyectan utilizando una función especificada.Key values are compared by using a specified comparer, and the elements of each group are projected by using a specified function.

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

Establece una correlación entre los elementos de dos secuencias en función de la igualdad de sus claves y agrupa los resultados.Correlates the elements of two sequences based on equality of keys and groups the results. El comparador de igualdad predeterminado se usa para comparar claves.The default equality comparer is used to compare keys.

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

Establece una correlación entre los elementos de dos secuencias basándose en la igualdad de clave y agrupa los resultados.Correlates the elements of two sequences based on key equality and groups the results. Se usa un IEqualityComparer<T> especificado para comparar claves.A specified IEqualityComparer<T> is used to compare keys.

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

Proporciona la intersección de conjuntos de dos secuencias utilizando el comparador de igualdad predeterminado para comparar los valores.Produces the set intersection of two sequences by using the default equality comparer to compare values.

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

Proporciona la intersección de conjuntos de dos secuencias utilizando el objeto IEqualityComparer<T> especificado para comparar los valores.Produces the set intersection of two sequences by using the specified IEqualityComparer<T> to compare values.

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

Establece la correlación de dos secuencias basándose en claves coincidentes.Correlates the elements of two sequences based on matching keys. El comparador de igualdad predeterminado se usa para comparar claves.The default equality comparer is used to compare keys.

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

Establece la correlación de dos secuencias basándose en claves coincidentes.Correlates the elements of two sequences based on matching keys. Se usa un IEqualityComparer<T> especificado para comparar claves.A specified IEqualityComparer<T> is used to compare keys.

Last<TSource>(IEnumerable<TSource>)

Devuelve el último elemento de una secuencia.Returns the last element of a sequence.

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

Devuelve el último elemento de una secuencia que satisface una condición especificada.Returns the last element of a sequence that satisfies a specified condition.

LastOrDefault<TSource>(IEnumerable<TSource>)

Devuelve el último elemento de una secuencia o un valor predeterminado si la secuencia no contiene elementos.Returns the last element of a sequence, or a default value if the sequence contains no elements.

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

Devuelve el último elemento de una secuencia que satisface una condición o un valor predeterminado si no se encuentra dicho elemento.Returns the last element of a sequence that satisfies a condition or a default value if no such element is found.

LongCount<TSource>(IEnumerable<TSource>)

Devuelve un valor Int64 que representa el número total de elementos de una secuencia.Returns an Int64 that represents the total number of elements in a sequence.

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

Devuelve un valor Int64 que representa el número de elementos de una secuencia que satisfacen una condición.Returns an Int64 that represents how many elements in a sequence satisfy a condition.

Max<TSource>(IEnumerable<TSource>)

Devuelve el valor máximo de una secuencia genérica.Returns the maximum value in a generic sequence.

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

Invoca una función de transformación en cada elemento de una secuencia y devuelve el valor Decimal máximo.Invokes a transform function on each element of a sequence and returns the maximum Decimal value.

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

Invoca una función de transformación en cada elemento de una secuencia y devuelve el valor Double máximo.Invokes a transform function on each element of a sequence and returns the maximum Double value.

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

Invoca una función de transformación en cada elemento de una secuencia y devuelve el valor Int32 máximo.Invokes a transform function on each element of a sequence and returns the maximum Int32 value.

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

Invoca una función de transformación en cada elemento de una secuencia y devuelve el valor Int64 máximo.Invokes a transform function on each element of a sequence and returns the maximum Int64 value.

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

Invoca una función de transformación en cada elemento de una secuencia y devuelve el valor Decimal máximo que acepta valores NULL.Invokes a transform function on each element of a sequence and returns the maximum nullable Decimal value.

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

Invoca una función de transformación en cada elemento de una secuencia y devuelve el valor Double máximo que acepta valores NULL.Invokes a transform function on each element of a sequence and returns the maximum nullable Double value.

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

Invoca una función de transformación en cada elemento de una secuencia y devuelve el valor Int32 máximo que acepta valores NULL.Invokes a transform function on each element of a sequence and returns the maximum nullable Int32 value.

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

Invoca una función de transformación en cada elemento de una secuencia y devuelve el valor Int64 máximo que acepta valores NULL.Invokes a transform function on each element of a sequence and returns the maximum nullable Int64 value.

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

Invoca una función de transformación en cada elemento de una secuencia y devuelve el valor Single máximo que acepta valores NULL.Invokes a transform function on each element of a sequence and returns the maximum nullable Single value.

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

Invoca una función de transformación en cada elemento de una secuencia y devuelve el valor Single máximo.Invokes a transform function on each element of a sequence and returns the maximum Single value.

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

Invoca una función de transformación en cada elemento de una secuencia genérica y devuelve el valor máximo resultante.Invokes a transform function on each element of a generic sequence and returns the maximum resulting value.

Min<TSource>(IEnumerable<TSource>)

Devuelve el valor mínimo de una secuencia genérica.Returns the minimum value in a generic sequence.

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

Invoca una función de transformación en cada elemento de una secuencia y devuelve el valor Decimal mínimo.Invokes a transform function on each element of a sequence and returns the minimum Decimal value.

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

Invoca una función de transformación en cada elemento de una secuencia y devuelve el valor Double mínimo.Invokes a transform function on each element of a sequence and returns the minimum Double value.

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

Invoca una función de transformación en cada elemento de una secuencia y devuelve el valor Int32 mínimo.Invokes a transform function on each element of a sequence and returns the minimum Int32 value.

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

Invoca una función de transformación en cada elemento de una secuencia y devuelve el valor Int64 mínimo.Invokes a transform function on each element of a sequence and returns the minimum Int64 value.

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

Invoca una función de transformación en cada elemento de una secuencia y devuelve el valor Decimal mínimo que acepta valores NULL.Invokes a transform function on each element of a sequence and returns the minimum nullable Decimal value.

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

Invoca una función de transformación en cada elemento de una secuencia y devuelve el valor Double mínimo que acepta valores NULL.Invokes a transform function on each element of a sequence and returns the minimum nullable Double value.

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

Invoca una función de transformación en cada elemento de una secuencia y devuelve el valor Int32 mínimo que acepta valores NULL.Invokes a transform function on each element of a sequence and returns the minimum nullable Int32 value.

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

Invoca una función de transformación en cada elemento de una secuencia y devuelve el valor Int64 mínimo que acepta valores NULL.Invokes a transform function on each element of a sequence and returns the minimum nullable Int64 value.

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

Invoca una función de transformación en cada elemento de una secuencia y devuelve el valor Single mínimo que acepta valores NULL.Invokes a transform function on each element of a sequence and returns the minimum nullable Single value.

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

Invoca una función de transformación en cada elemento de una secuencia y devuelve el valor Single mínimo.Invokes a transform function on each element of a sequence and returns the minimum Single value.

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

Invoca una función de transformación en cada elemento de una secuencia genérica y devuelve el valor mínimo resultante.Invokes a transform function on each element of a generic sequence and returns the minimum resulting value.

OfType<TResult>(IEnumerable)

Filtra los elementos de IEnumerable en función de un tipo especificado.Filters the elements of an IEnumerable based on a specified type.

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

Ordena de manera ascendente los elementos de una secuencia en función de una clave.Sorts the elements of a sequence in ascending order according to a key.

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

Ordena de manera ascendente los elementos de una secuencia utilizando un comparador especificado.Sorts the elements of a sequence in ascending order by using a specified comparer.

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

Ordena de manera descendente los elementos de una secuencia en función de una clave.Sorts the elements of a sequence in descending order according to a key.

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

Ordena de manera descendente los elementos de una secuencia utilizando un comparador especificado.Sorts the elements of a sequence in descending order by using a specified comparer.

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

Agrega un valor al principio de la secuencia.Adds a value to the beginning of the sequence.

Reverse<TSource>(IEnumerable<TSource>)

Invierte el orden de los elementos de una secuencia.Inverts the order of the elements in a sequence.

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

Proyecta cada elemento de una secuencia a un nuevo formulario.Projects each element of a sequence into a new form.

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

Proyecta cada elemento de una secuencia en un nuevo formulario incorporando el índice del elemento.Projects each element of a sequence into a new form by incorporating the element's index.

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

Proyecta cada elemento de una secuencia en una interfaz IEnumerable<T> y reduce las secuencias resultantes en una secuencia.Projects each element of a sequence to an IEnumerable<T> and flattens the resulting sequences into one sequence.

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

Proyecta cada elemento de una secuencia en una interfaz IEnumerable<T> y reduce las secuencias resultantes en una secuencia.Projects each element of a sequence to an IEnumerable<T>, and flattens the resulting sequences into one sequence. El índice de cada elemento de origen se utiliza en el formulario proyectado de ese elemento.The index of each source element is used in the projected form of that element.

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

Proyecta cada elemento de una secuencia en IEnumerable<T>, reduce las secuencias resultantes en una única secuencia e invoca una función del selector de resultados en cada elemento.Projects each element of a sequence to an IEnumerable<T>, flattens the resulting sequences into one sequence, and invokes a result selector function on each element therein.

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

Proyecta cada elemento de una secuencia en IEnumerable<T>, reduce las secuencias resultantes en una única secuencia e invoca una función del selector de resultados en cada elemento.Projects each element of a sequence to an IEnumerable<T>, flattens the resulting sequences into one sequence, and invokes a result selector function on each element therein. El índice de cada elemento de origen se utiliza en el formulario proyectado intermedio de ese elemento.The index of each source element is used in the intermediate projected form of that element.

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

Determina si dos secuencias son iguales; para ello, se comparan sus elementos mediante el comparador de igualdad predeterminado para su tipo.Determines whether two sequences are equal by comparing the elements by using the default equality comparer for their type.

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

Determina si dos secuencias son iguales; para ello, compara sus elementos utilizando una interfaz IEqualityComparer<T> especificada.Determines whether two sequences are equal by comparing their elements by using a specified IEqualityComparer<T>.

Single<TSource>(IEnumerable<TSource>)

Devuelve el único elemento de una secuencia y produce una excepción si no hay exactamente un elemento en la secuencia.Returns the only element of a sequence, and throws an exception if there is not exactly one element in the sequence.

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

Devuelve el único elemento de una secuencia que cumpla una condición especificada y produce una excepción si existe más de un elemento de este tipo.Returns the only element of a sequence that satisfies a specified condition, and throws an exception if more than one such element exists.

SingleOrDefault<TSource>(IEnumerable<TSource>)

Devuelve el único elemento de una secuencia o un valor predeterminado si la secuencia está vacía; este método produce una excepción si hay más de un elemento en la secuencia.Returns the only element of a sequence, or a default value if the sequence is empty; this method throws an exception if there is more than one element in the sequence.

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

Devuelve el único elemento de una secuencia que cumpla la condición especificada, o bien, un valor predeterminado si ese elemento no existe; este método produce una excepción si varios elementos cumplen la condición.Returns the only element of a sequence that satisfies a specified condition or a default value if no such element exists; this method throws an exception if more than one element satisfies the condition.

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

Omite un número especificado de elementos en una secuencia y luego devuelve los elementos restantes.Bypasses a specified number of elements in a sequence and then returns the remaining elements.

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

Devuelve una nueva colección que contiene los elementos de source con los últimos elementos de count de la colección de origen omitida.Returns a new enumerable collection that contains the elements from source with the last count elements of the source collection omitted.

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

Omite los elementos de una secuencia en tanto que el valor de una condición especificada sea true y luego devuelve los elementos restantes.Bypasses elements in a sequence as long as a specified condition is true and then returns the remaining elements.

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

Omite los elementos de una secuencia en tanto que el valor de una condición especificada sea true y luego devuelve los elementos restantes.Bypasses elements in a sequence as long as a specified condition is true and then returns the remaining elements. El índice del elemento se usa en la lógica de la función de predicado.The element's index is used in the logic of the predicate function.

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

Calcula la suma de una secuencia de valores Decimal que se obtiene al invocar una función de transformación en cada elemento de la secuencia de entrada.Computes the sum of the sequence of Decimal values that are obtained by invoking a transform function on each element of the input sequence.

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

Calcula la suma de una secuencia de valores Double que se obtiene al invocar una función de transformación en cada elemento de la secuencia de entrada.Computes the sum of the sequence of Double values that are obtained by invoking a transform function on each element of the input sequence.

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

Calcula la suma de una secuencia de valores Int32 que se obtiene al invocar una función de transformación en cada elemento de la secuencia de entrada.Computes the sum of the sequence of Int32 values that are obtained by invoking a transform function on each element of the input sequence.

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

Calcula la suma de una secuencia de valores Int64 que se obtiene al invocar una función de transformación en cada elemento de la secuencia de entrada.Computes the sum of the sequence of Int64 values that are obtained by invoking a transform function on each element of the input sequence.

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

Calcula la suma de una secuencia de valores Decimal que aceptan valores NULL que se obtiene al invocar una función de transformación en cada elemento de la secuencia de entrada.Computes the sum of the sequence of nullable Decimal values that are obtained by invoking a transform function on each element of the input sequence.

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

Calcula la suma de una secuencia de valores Double que aceptan valores NULL que se obtiene al invocar una función de transformación en cada elemento de la secuencia de entrada.Computes the sum of the sequence of nullable Double values that are obtained by invoking a transform function on each element of the input sequence.

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

Calcula la suma de una secuencia de valores Int32 que aceptan valores NULL que se obtiene al invocar una función de transformación en cada elemento de la secuencia de entrada.Computes the sum of the sequence of nullable Int32 values that are obtained by invoking a transform function on each element of the input sequence.

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

Calcula la suma de una secuencia de valores Int64 que aceptan valores NULL que se obtiene al invocar una función de transformación en cada elemento de la secuencia de entrada.Computes the sum of the sequence of nullable Int64 values that are obtained by invoking a transform function on each element of the input sequence.

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

Calcula la suma de una secuencia de valores Single que aceptan valores NULL que se obtiene al invocar una función de transformación en cada elemento de la secuencia de entrada.Computes the sum of the sequence of nullable Single values that are obtained by invoking a transform function on each element of the input sequence.

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

Calcula la suma de una secuencia de valores Single que se obtiene al invocar una función de transformación en cada elemento de la secuencia de entrada.Computes the sum of the sequence of Single values that are obtained by invoking a transform function on each element of the input sequence.

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

Devuelve un número especificado de elementos contiguos desde el principio de una secuencia.Returns a specified number of contiguous elements from the start of a sequence.

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

Devuelve una nueva colección enumerable que contiene los últimos elementos count de source.Returns a new enumerable collection that contains the last count elements from source.

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

Devuelve los elementos de una secuencia en tanto que el valor de una condición especificada sea true.Returns elements from a sequence as long as a specified condition is true.

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

Devuelve los elementos de una secuencia en tanto que el valor de una condición especificada sea true.Returns elements from a sequence as long as a specified condition is true. El índice del elemento se usa en la lógica de la función de predicado.The element's index is used in the logic of the predicate function.

ToArray<TSource>(IEnumerable<TSource>)

Crea una matriz a partir de un IEnumerable<T>.Creates an array from a IEnumerable<T>.

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

Crea una clase Dictionary<TKey,TValue> a partir de una interfaz IEnumerable<T> según una función del selector de claves especificada.Creates a Dictionary<TKey,TValue> from an IEnumerable<T> according to a specified key selector function.

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

Crea un objeto Dictionary<TKey,TValue> a partir de un objeto IEnumerable<T> según una función del selector de claves especificada y el comparador de claves.Creates a Dictionary<TKey,TValue> from an IEnumerable<T> according to a specified key selector function and key comparer.

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

Crea un objeto Dictionary<TKey,TValue> a partir de un objeto IEnumerable<T> según el selector de claves especificado y las funciones del selector de elementos.Creates a Dictionary<TKey,TValue> from an IEnumerable<T> according to specified key selector and element selector functions.

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

Crea un objeto Dictionary<TKey,TValue> a partir de un objeto IEnumerable<T> según una función del selector de claves especificada, un comparador y una función del selector de elementos.Creates a Dictionary<TKey,TValue> from an IEnumerable<T> according to a specified key selector function, a comparer, and an element selector function.

ToHashSet<TSource>(IEnumerable<TSource>)

Crea un HashSet<T> a partir de un IEnumerable<T>.Creates a HashSet<T> from an IEnumerable<T>.

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

Crea un objeto HashSet<T> a partir de una instancia de IEnumerable<T> mediante comparer para comparar claves.Creates a HashSet<T> from an IEnumerable<T> using the comparer to compare keys.

ToList<TSource>(IEnumerable<TSource>)

Crea un List<T> a partir de un IEnumerable<T>.Creates a List<T> from an IEnumerable<T>.

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

Crea una clase Lookup<TKey,TElement> a partir de una interfaz IEnumerable<T> según una función del selector de claves especificada.Creates a Lookup<TKey,TElement> from an IEnumerable<T> according to a specified key selector function.

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

Crea un objeto Lookup<TKey,TElement> a partir de un objeto IEnumerable<T> según una función del selector de claves especificada y el comparador de claves.Creates a Lookup<TKey,TElement> from an IEnumerable<T> according to a specified key selector function and key comparer.

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

Crea un objeto Lookup<TKey,TElement> a partir de un objeto IEnumerable<T> según el selector de claves especificado y las funciones del selector de elementos.Creates a Lookup<TKey,TElement> from an IEnumerable<T> according to specified key selector and element selector functions.

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

Crea un objeto Lookup<TKey,TElement> a partir de un objeto IEnumerable<T> según una función del selector de claves, un comparador y una función del selector de elementos especificados.Creates a Lookup<TKey,TElement> from an IEnumerable<T> according to a specified key selector function, a comparer and an element selector function.

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

Proporciona la unión de conjuntos de dos secuencias utilizando el comparador de igualdad predeterminado.Produces the set union of two sequences by using the default equality comparer.

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

Proporciona la unión de conjuntos de dos secuencias a través de un objeto IEqualityComparer<T> especificado.Produces the set union of two sequences by using a specified IEqualityComparer<T>.

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

Filtra una secuencia de valores en función de un predicado.Filters a sequence of values based on a predicate.

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

Filtra una secuencia de valores en función de un predicado.Filters a sequence of values based on a predicate. El índice de cada elemento se usa en la lógica de la función de predicado.Each element's index is used in the logic of the predicate function.

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

Genera una secuencia de tuplas con elementos a partir de las dos secuencias especificadas.Produces a sequence of tuples with elements from the two specified sequences.

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

Aplica la función especificada a los elementos correspondientes de dos secuencias, lo que genera una secuencia de resultados.Applies a specified function to the corresponding elements of two sequences, producing a sequence of the results.

AsParallel(IEnumerable)

Habilita la paralelización de una consulta.Enables parallelization of a query.

AsParallel<TSource>(IEnumerable<TSource>)

Habilita la paralelización de una consulta.Enables parallelization of a query.

AsQueryable(IEnumerable)

Convierte una interfaz IEnumerable en IQueryable.Converts an IEnumerable to an IQueryable.

AsQueryable<TElement>(IEnumerable<TElement>)

Convierte un parámetro IEnumerable<T> genérico en un parámetro IQueryable<T> genérico.Converts a generic IEnumerable<T> to a generic IQueryable<T>.

Ancestors<T>(IEnumerable<T>)

Devuelve una colección de elementos que contiene los antecesores de todos los nodos de la colección de origen.Returns a collection of elements that contains the ancestors of every node in the source collection.

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

Devuelve una colección de elementos filtrada que contiene los antecesores de todos los nodos de la colección de origen.Returns a filtered collection of elements that contains the ancestors of every node in the source collection. En la colección sólo se incluyen los elementos que tienen un objeto XName coincidente.Only elements that have a matching XName are included in the collection.

DescendantNodes<T>(IEnumerable<T>)

Devuelve una colección de los nodos descendientes de todos los documentos y elementos de la colección de origen.Returns a collection of the descendant nodes of every document and element in the source collection.

Descendants<T>(IEnumerable<T>)

Devuelve una colección de elementos que contiene los elementos descendientes de todos los elementos y documentos de la colección de origen.Returns a collection of elements that contains the descendant elements of every element and document in the source collection.

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

Devuelve una colección filtrada de elementos que contiene los elementos descendientes de todos los elementos y documentos de la colección de origen.Returns a filtered collection of elements that contains the descendant elements of every element and document in the source collection. En la colección sólo se incluyen los elementos que tienen un objeto XName coincidente.Only elements that have a matching XName are included in the collection.

Elements<T>(IEnumerable<T>)

Devuelve una colección de los elementos secundarios de todos los elementos y documentos de la colección de origen.Returns a collection of the child elements of every element and document in the source collection.

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

Devuelve una colección filtrada de los elementos secundarios de todos los elementos y documentos de la colección de origen.Returns a filtered collection of the child elements of every element and document in the source collection. En la colección sólo se incluyen los elementos que tienen un objeto XName coincidente.Only elements that have a matching XName are included in the collection.

InDocumentOrder<T>(IEnumerable<T>)

Devuelve una colección de nodos que contiene todos los nodos de la colección de origen, clasificados por documento.Returns a collection of nodes that contains all nodes in the source collection, sorted in document order.

Nodes<T>(IEnumerable<T>)

Devuelve una colección de los nodos secundarios de todos los documentos y elementos de la colección de origen.Returns a collection of the child nodes of every document and element in the source collection.

Remove<T>(IEnumerable<T>)

Quita todos los nodos de la colección de origen de su nodo primario.Removes every node in the source collection from its parent node.

Applies to

See also