KeyedCollection<TKey,TItem> Classe
Definição
Fornece a classe base abstrata para uma coleção cujas chaves são incorporadas nos 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>
[<System.Runtime.InteropServices.ComVisible(false)>]
[<System.Serializable>]
type KeyedCollection<'Key, 'Item> = class
inherit Collection<'Item>
Public MustInherit Class KeyedCollection(Of TKey, TItem)
Inherits Collection(Of TItem)
Parâmetros de tipo
- TKey
O tipo das chaves da coleção.The type of keys in the collection.
- TItem
O tipo de itens na coleção.The type of items in the collection.
- Herança
- Derivado
- Atributos
Exemplos
Esta seção contém dois exemplos de código.This section contains two code examples. O primeiro exemplo mostra o código mínimo necessário para derivar de KeyedCollection<TKey,TItem> e demonstra muitos dos métodos herdados.The first example shows the minimum code required to derive from KeyedCollection<TKey,TItem>, and demonstrates many of the inherited methods. O segundo exemplo mostra como substituir os métodos protegidos do KeyedCollection<TKey,TItem> para fornecer o comportamento personalizado.The second example shows how to override the protected methods of KeyedCollection<TKey,TItem> to provide custom behavior.
Exemplo 1Example 1
Este exemplo de código mostra o código mínimo necessário a ser derivado de uma classe de coleção de KeyedCollection<TKey,TItem>: substituindo o método GetKeyForItem e fornecendo um construtor público que representa um construtor de classe 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. O exemplo de código também demonstra muitas das propriedades e dos métodos herdados das classes KeyedCollection<TKey,TItem> e Collection<T>.The code example also demonstrates many of the properties and methods inherited from KeyedCollection<TKey,TItem> and Collection<T> classes.
A classe SimpleOrder é uma lista muito simples de requisição que contém objetos OrderItem, cada um representando um item de linha na ordem.The SimpleOrder class is a very simple requisition list that contains OrderItem objects, each of which represents a line item in the order. A chave de OrderItem é imutável, uma consideração importante para classes que derivam de KeyedCollection<TKey,TItem>.The key of OrderItem is immutable, an important consideration for classes that derive from KeyedCollection<TKey,TItem>. Para um exemplo de código que usa chaves mutáveis, consulte 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
Exemplo 2Example 2
O exemplo de código a seguir mostra como substituir os métodos InsertItem, RemoveItem e ClearItems, SetItem protegidos para fornecer um comportamento personalizado para os métodos Add, Remove e Clear, além de definir a propriedade Item[] padrão (o indexador em C#).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#). O comportamento personalizado fornecido neste exemplo é um evento de notificação chamado Changed, gerado ao final de cada um dos métodos substituídos.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.
O exemplo de código cria a classe SimpleOrder, que deriva do KeyedCollection<TKey,TItem> e representa um formulário de pedido simples.The code example creates the SimpleOrder class, which derives from KeyedCollection<TKey,TItem> and represents a simple order form. O formulário do pedido contém objetos OrderItem representando itens ordenados.The order form contains OrderItem objects representing items ordered. O exemplo de código também cria uma classe SimpleOrderChangedEventArgs para conter informações do evento, e uma enumeração para identificar o tipo de alteração.The code example also creates a SimpleOrderChangedEventArgs class to contain the event information, and an enumeration to identify the type of change.
O exemplo de código demonstra o comportamento personalizado chamando as propriedades e os métodos da classe derivada, no método Main da classe 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.
Este exemplo de código usa objetos com chaves imutáveis.This code example uses objects with immutable keys. Para um exemplo de código que usa chaves mutáveis, consulte 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.
Comentários
A KeyedCollection<TKey,TItem> classe fornece a (1) recuperação indexada e recuperação com chave que se aproxima de o (1).The KeyedCollection<TKey,TItem> class provides both O(1) indexed retrieval and keyed retrieval that approaches O(1). É um tipo abstrato ou mais precisamente um conjunto infinito de tipos abstratos, porque cada um de seus tipos genéricos construídos é uma classe base abstrata.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 o tipo de coleção do tipo construído apropriado.To use KeyedCollection<TKey,TItem>, derive your collection type from the appropriate constructed type.
A KeyedCollection<TKey,TItem> classe é uma híbrida entre uma coleção baseada na IList<T> interface genérica e uma coleção baseada na IDictionary<TKey,TValue> interface genérica.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. Como as coleções baseadas na IList<T> interface genérica, KeyedCollection<TKey,TItem> é uma lista indexada de itens.Like collections based on the IList<T> generic interface, KeyedCollection<TKey,TItem> is an indexed list of items. Como as coleções baseadas na IDictionary<TKey,TValue> interface genérica, KeyedCollection<TKey,TItem> tem uma chave associada a cada elemento.Like collections based on the IDictionary<TKey,TValue> generic interface, KeyedCollection<TKey,TItem> has a key associated with each element.
Ao contrário dos dicionários, um elemento de KeyedCollection<TKey,TItem> não é um par de chave/valor; em vez disso, o elemento inteiro é o valor e a chave é inserida dentro do 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 exemplo, um elemento de uma coleção derivada de KeyedCollection\<String,String> ( KeyedCollection(Of String, String) em Visual Basic) pode 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." onde o valor é "John Doe Jr."where the value is "John Doe Jr." e a chave é "Doe"; ou uma coleção de registros de funcionários que contém chaves inteiras pode ser derivada 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>. O GetKeyForItem método abstract extrai a chave do elemento.The abstract GetKeyForItem method extracts the key from the element.
Por padrão, o KeyedCollection<TKey,TItem> inclui um dicionário de pesquisa que você pode obter com a Dictionary propriedade.By default, the KeyedCollection<TKey,TItem> includes a lookup dictionary that you can obtain with the Dictionary property. Quando um item é adicionado ao KeyedCollection<TKey,TItem>, a chave do item será extraída uma vez e salva no dicionário de pesquisa para pesquisas mais rápidas.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. Esse comportamento é substituído especificando-se um limite de criação de dicionário quando você cria o KeyedCollection<TKey,TItem> .This behavior is overridden by specifying a dictionary creation threshold when you create the KeyedCollection<TKey,TItem>. O dicionário de pesquisa é criado na primeira vez em que o número de elementos excede esse limite.The lookup dictionary is created the first time the number of elements exceeds that threshold. Se você especificar-1 como o limite, o dicionário de pesquisa nunca será criado.If you specify -1 as the threshold, the lookup dictionary is never created.
Observação
Quando o dicionário de pesquisa interno é usado, ele contém referências a todos os itens na coleção se TItem for um tipo de referência, ou cópias de todos os itens na coleção se TItem for um 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. Assim, o uso do dicionário de pesquisa poderá não ser apropriado se TItem for um tipo de valor.Thus, using the lookup dictionary may not be appropriate if TItem is a value type.
Você pode acessar um item por seu índice ou chave usando a Item[] propriedade.You can access an item by its index or key by using the Item[] property. Você pode adicionar itens sem uma chave, mas esses itens podem ser acessados posteriormente somente pelo índice.You can add items without a key, but these items can subsequently be accessed only by index.
Construtores
| KeyedCollection<TKey,TItem>() |
Inicializa uma nova instância da classe KeyedCollection<TKey,TItem> que usa o comparador de igualdade padrão.Initializes a new instance of the KeyedCollection<TKey,TItem> class that uses the default equality comparer. |
| KeyedCollection<TKey,TItem>(IEqualityComparer<TKey>) |
Inicializa uma nova instância da classe KeyedCollection<TKey,TItem> que usa o comparador de igualdade especificado.Initializes a new instance of the KeyedCollection<TKey,TItem> class that uses the specified equality comparer. |
| KeyedCollection<TKey,TItem>(IEqualityComparer<TKey>, Int32) |
Inicializa uma nova instância da classe KeyedCollection<TKey,TItem> que usa o comparador de igualdade especificado e cria um dicionário de pesquisa quando o limite especificado é excedido.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. |
Propriedades
| Comparer |
Obtém o comparador de igualdade genérico que é usado para determinar a igualdade de chaves na coleção.Gets the generic equality comparer that is used to determine equality of keys in the collection. |
| Count |
Obtém o número de elementos realmente contidos no Collection<T>.Gets the number of elements actually contained in the Collection<T>. (Herdado de Collection<T>) |
| Dictionary |
Obtém o dicionário de pesquisa do KeyedCollection<TKey,TItem>.Gets the lookup dictionary of the KeyedCollection<TKey,TItem>. |
| Item[Int32] |
Obtém ou define o elemento no índice especificado.Gets or sets the element at the specified index. (Herdado de Collection<T>) |
| Item[TKey] |
Obtém o elemento com a chave especificada.Gets the element with the specified key. |
| Items |
Obtém um wrapper IList<T> ao redor de Collection<T>.Gets a IList<T> wrapper around the Collection<T>. (Herdado de Collection<T>) |
Métodos
| Add(T) |
Adiciona um objeto ao final do Collection<T>.Adds an object to the end of the Collection<T>. (Herdado de Collection<T>) |
| ChangeItemKey(TItem, TKey) |
Altera a chave associada ao elemento especificado no dicionário de pesquisa.Changes the key associated with the specified element in the lookup dictionary. |
| Clear() |
Remove todos os elementos do Collection<T>.Removes all elements from the Collection<T>. (Herdado de Collection<T>) |
| ClearItems() |
Remove todos os elementos do KeyedCollection<TKey,TItem>.Removes all elements from the KeyedCollection<TKey,TItem>. |
| Contains(TKey) |
Determina se a coleção contém um elemento com a chave especificada.Determines whether the collection contains an element with the specified key. |
| CopyTo(T[], Int32) |
Copia todo o Collection<T> em um Array unidimensional compatível, começando no índice especificado da matriz de destino.Copies the entire Collection<T> to a compatible one-dimensional Array, starting at the specified index of the target array. (Herdado de Collection<T>) |
| Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual.Determines whether the specified object is equal to the current object. (Herdado de Object) |
| GetEnumerator() |
Retorna um enumerador que itera por meio de Collection<T>.Returns an enumerator that iterates through the Collection<T>. (Herdado de Collection<T>) |
| GetHashCode() |
Serve como a função de hash padrão.Serves as the default hash function. (Herdado de Object) |
| GetKeyForItem(TItem) |
Quando implementado em uma classe derivada, extrai a chave do elemento especificado.When implemented in a derived class, extracts the key from the specified element. |
| GetType() |
Obtém o Type da instância atual.Gets the Type of the current instance. (Herdado de Object) |
| IndexOf(T) |
Pesquisa o objeto especificado e retorna o índice baseado em zero da primeira ocorrência dentro de todo o Collection<T>.Searches for the specified object and returns the zero-based index of the first occurrence within the entire Collection<T>. (Herdado de Collection<T>) |
| Insert(Int32, T) |
Insere um elemento no Collection<T>, no índice especificado.Inserts an element into the Collection<T> at the specified index. (Herdado de Collection<T>) |
| InsertItem(Int32, T) |
Insere um elemento no Collection<T>, no índice especificado.Inserts an element into the Collection<T> at the specified index. (Herdado de Collection<T>) |
| InsertItem(Int32, TItem) |
Insere um elemento no KeyedCollection<TKey,TItem>, no índice especificado.Inserts an element into the KeyedCollection<TKey,TItem> at the specified index. |
| MemberwiseClone() |
Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object. (Herdado de Object) |
| Remove(TKey) |
Remove o elemento com a chave especificada do KeyedCollection<TKey,TItem>.Removes the element with the specified key from the KeyedCollection<TKey,TItem>. |
| RemoveAt(Int32) |
Remove o elemento no índice especificado do Collection<T>.Removes the element at the specified index of the Collection<T>. (Herdado de Collection<T>) |
| RemoveItem(Int32) |
Remove o elemento no índice especificado do KeyedCollection<TKey,TItem>.Removes the element at the specified index of the KeyedCollection<TKey,TItem>. |
| SetItem(Int32, T) |
Substitui o elemento no índice especificado.Replaces the element at the specified index. (Herdado de Collection<T>) |
| SetItem(Int32, TItem) |
Substitui o item no índice especificado pelo item especificado.Replaces the item at the specified index with the specified item. |
| ToString() |
Retorna uma cadeia de caracteres que representa o objeto atual.Returns a string that represents the current object. (Herdado de Object) |
| TryGetValue(TKey, TItem) |
Tenta obter um item da coleção usando a chave especificada.Tries to get an item from the collection using the specified key. |
Implantações explícitas de interface
| ICollection.CopyTo(Array, Int32) |
Copia os elementos do ICollection para um Array, começando em um determinado índice Array.Copies the elements of the ICollection to an Array, starting at a particular Array index. (Herdado de Collection<T>) |
| ICollection.IsSynchronized |
Obtém um valor que indica se o acesso à ICollection é sincronizado (thread-safe).Gets a value indicating whether access to the ICollection is synchronized (thread safe). (Herdado de Collection<T>) |
| ICollection.SyncRoot |
Obtém um objeto que pode ser usado para sincronizar o acesso ao ICollection.Gets an object that can be used to synchronize access to the ICollection. (Herdado de Collection<T>) |
| ICollection<T>.IsReadOnly |
Obtém um valor que indica se o ICollection<T> é somente leitura.Gets a value indicating whether the ICollection<T> is read-only. (Herdado de Collection<T>) |
| IEnumerable.GetEnumerator() |
Retorna um enumerador que itera em uma coleção.Returns an enumerator that iterates through a collection. (Herdado de Collection<T>) |
| IList.Add(Object) |
Adiciona um item ao IList.Adds an item to the IList. (Herdado de Collection<T>) |
| IList.Contains(Object) |
Determinará se o IList contiver um valor específico.Determines whether the IList contains a specific value. (Herdado de Collection<T>) |
| IList.IndexOf(Object) |
Determina o índice de um item específico em IList.Determines the index of a specific item in the IList. (Herdado de Collection<T>) |
| IList.Insert(Int32, Object) |
Insere um item no IList no índice especificado.Inserts an item into the IList at the specified index. (Herdado de Collection<T>) |
| IList.IsFixedSize |
Obtém um valor que indica se o IList tem um tamanho fixo.Gets a value indicating whether the IList has a fixed size. (Herdado de Collection<T>) |
| IList.IsReadOnly |
Obtém um valor que indica se o IList é somente leitura.Gets a value indicating whether the IList is read-only. (Herdado de Collection<T>) |
| IList.Item[Int32] |
Obtém ou define o elemento no índice especificado.Gets or sets the element at the specified index. (Herdado de Collection<T>) |
| IList.Remove(Object) |
Remove a primeira ocorrência de um objeto específico do IList.Removes the first occurrence of a specific object from the IList. (Herdado de Collection<T>) |
Métodos de Extensão
| ToImmutableArray<TSource>(IEnumerable<TSource>) |
Cria uma matriz imutável com base na coleção especificada.Creates an immutable array from the specified collection. |
| ToImmutableDictionary<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>) |
Constrói um dicionário imutável de uma coleção existente de elementos, aplicando uma função de transformação nas chaves de origem.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>) |
Constrói um dicionário imutável com base em alguma transformação de uma sequência.Constructs an immutable dictionary based on some transformation of a sequence. |
| ToImmutableDictionary<TSource,TKey,TValue>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TValue>) |
Enumera e transforma uma sequência e produz um dicionário imutável com base em seu conteúdo.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 e transforma uma sequência e produz um dicionário imutável com base em seu conteúdo usando o comparador de chave 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 e transforma uma sequência e produz um dicionário imutável com base em seu conteúdo usando os comparadores de chave e valor especificados.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 uma sequência e produz um conjunto de hash imutável de seu conteúdo.Enumerates a sequence and produces an immutable hash set of its contents. |
| ToImmutableHashSet<TSource>(IEnumerable<TSource>, IEqualityComparer<TSource>) |
Enumera uma sequência, produz um conjunto de hash imutável de seu conteúdo e usa o comparador de igualdade especificado para o 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 uma sequência e produz uma lista imutável de seu conteúdo.Enumerates a sequence and produces an immutable list of its contents. |
| ToImmutableSortedDictionary<TSource,TKey,TValue>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TValue>) |
Enumera e transforma uma sequência e produz um dicionário classificado imutável com base em seu conteúdo.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 e transforma uma sequência e produz um dicionário classificado imutável com base em seu conteúdo usando o comparador de chave 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 e transforma uma sequência e produz um dicionário classificado imutável com base em seu conteúdo usando os comparadores de chave e valor especificados.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 uma sequência e produz um conjunto classificado imutável de seu conteúdo.Enumerates a sequence and produces an immutable sorted set of its contents. |
| ToImmutableSortedSet<TSource>(IEnumerable<TSource>, IComparer<TSource>) |
Enumera uma sequência, produz um conjunto classificado imutável de seu conteúdo e usa o comparador especificado.Enumerates a sequence, produces an immutable sorted set of its contents, and uses the specified comparer. |
| CopyToDataTable<T>(IEnumerable<T>) |
Retorna um DataTable que contém cópias dos objetos DataRow, dado um objeto IEnumerable<T> de entrada em que o parâmetro genérico |
| CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption) |
Copia objetos DataRow no DataTable especificado, dado um objeto IEnumerable<T> de entrada em que o parâmetro genérico |
| CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption, FillErrorEventHandler) |
Copia objetos DataRow no DataTable especificado, dado um objeto IEnumerable<T> de entrada em que o parâmetro genérico |
| Aggregate<TSource>(IEnumerable<TSource>, Func<TSource,TSource,TSource>) |
Aplica uma função de acumulador a uma sequência.Applies an accumulator function over a sequence. |
| Aggregate<TSource,TAccumulate>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate,TSource,TAccumulate>) |
Aplica uma função de acumulador a uma sequência.Applies an accumulator function over a sequence. O valor de semente especificado é usado como o valor inicial do 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 uma função de acumulador a uma sequência.Applies an accumulator function over a sequence. O valor de semente especificado é usado como o valor inicial do acumulador e a função especificada é usada para selecionar o valor do resultado.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 se todos os elementos de uma sequência atendem a uma condição.Determines whether all elements of a sequence satisfy a condition. |
| Any<TSource>(IEnumerable<TSource>) |
Determina se uma sequência contém elementos.Determines whether a sequence contains any elements. |
| Any<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) |
Determina se algum elemento de uma sequência atende a uma condição.Determines whether any element of a sequence satisfies a condition. |
| Append<TSource>(IEnumerable<TSource>, TSource) |
Acrescenta um valor ao final da sequência.Appends a value to the end of the sequence. |
| AsEnumerable<TSource>(IEnumerable<TSource>) |
Retorna a entrada digitada como IEnumerable<T>.Returns the input typed as IEnumerable<T>. |
| Average<TSource>(IEnumerable<TSource>, Func<TSource,Decimal>) |
Calcula a média de uma sequência de valores Decimal obtidos pela invocação de uma função de transformação em cada elemento da sequência 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 a média de uma sequência de valores Double obtidos pela invocação de uma função de transformação em cada elemento da sequência 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 a média de uma sequência de valores Int32 obtidos pela invocação de uma função de transformação em cada elemento da sequência 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 a média de uma sequência de valores Int64 obtidos pela invocação de uma função de transformação em cada elemento da sequência 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 a média de uma sequência de valores Decimal que permitem valor nulo obtidos pela invocação de uma função de transformação em cada elemento da sequência 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 a média de uma sequência de valores Double que permitem valor nulo obtidos pela invocação de uma função de transformação em cada elemento da sequência 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 a média de uma sequência de valores Int32 que permitem valor nulo obtidos pela invocação de uma função de transformação em cada elemento da sequência 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 a média de uma sequência de valores Int64 que permitem valor nulo obtidos pela invocação de uma função de transformação em cada elemento da sequência 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 a média de uma sequência de valores Single que permitem valor nulo obtidos pela invocação de uma função de transformação em cada elemento da sequência 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 a média de uma sequência de valores Single obtidos pela invocação de uma função de transformação em cada elemento da sequência 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) |
Converte os elementos de um IEnumerable para o tipo especificado.Casts the elements of an IEnumerable to the specified type. |
| Concat<TSource>(IEnumerable<TSource>, IEnumerable<TSource>) |
Concatena duas sequências.Concatenates two sequences. |
| Contains<TSource>(IEnumerable<TSource>, TSource) |
Determina se uma sequência contém um elemento especificado usando o comparador de igualdade padrão.Determines whether a sequence contains a specified element by using the default equality comparer. |
| Contains<TSource>(IEnumerable<TSource>, TSource, IEqualityComparer<TSource>) |
Determina se uma sequência contém um elemento especificado usando um IEqualityComparer<T> especificado.Determines whether a sequence contains a specified element by using a specified IEqualityComparer<T>. |
| Count<TSource>(IEnumerable<TSource>) |
Retorna o número de elementos em uma sequência.Returns the number of elements in a sequence. |
| Count<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) |
Retorna um número que representa quantos elementos na sequência especificada atendem a uma condição.Returns a number that represents how many elements in the specified sequence satisfy a condition. |
| DefaultIfEmpty<TSource>(IEnumerable<TSource>) |
Retornará os elementos da sequência especificada ou o valor padrão do parâmetro de tipo em uma coleção de singletons se a sequência estiver vazia.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) |
Retorna os elementos da sequência especificada ou o valor especificado em uma coleção de singletons se a sequência está vazia.Returns the elements of the specified sequence or the specified value in a singleton collection if the sequence is empty. |
| Distinct<TSource>(IEnumerable<TSource>) |
Retorna os elementos distintos de uma sequência usando o comparador de igualdade padrão para comparar valores.Returns distinct elements from a sequence by using the default equality comparer to compare values. |
| Distinct<TSource>(IEnumerable<TSource>, IEqualityComparer<TSource>) |
Retorna os elementos distintos de uma sequência usando um IEqualityComparer<T> especificado para comparar valores.Returns distinct elements from a sequence by using a specified IEqualityComparer<T> to compare values. |
| ElementAt<TSource>(IEnumerable<TSource>, Int32) |
Retorna o elemento de um índice especificado em uma sequência.Returns the element at a specified index in a sequence. |
| ElementAtOrDefault<TSource>(IEnumerable<TSource>, Int32) |
Retorna o elemento em um índice especificado em uma sequência ou um valor padrão se o índice estiver fora do 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>) |
Produz a diferença de conjunto de duas sequências usando o comparador de igualdade padrão para comparar os 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>) |
Produz a diferença de conjunto de duas sequências usando o IEqualityComparer<T> especificado para comparar os valores.Produces the set difference of two sequences by using the specified IEqualityComparer<T> to compare values. |
| First<TSource>(IEnumerable<TSource>) |
Retorna o primeiro elemento de uma sequência.Returns the first element of a sequence. |
| First<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) |
Retorna o primeiro elemento em uma sequência que satisfaz uma condição especificada.Returns the first element in a sequence that satisfies a specified condition. |
| FirstOrDefault<TSource>(IEnumerable<TSource>) |
Retorna o primeiro elemento de uma sequência ou um valor padrão se a sequência não contém 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>) |
Retorna o primeiro elemento da sequência que satisfaz uma condição ou um valor padrão, caso esse elemento não seja encontrado.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 os elementos de uma sequência de acordo com uma função de seletor de chave 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 os elementos de uma sequência de acordo com uma função do seletor de chave especificada e compara as chaves usando um 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 os elementos de uma sequência de acordo com a função de seletor de chave especificada e projeta os elementos de cada grupo usando uma função especificada.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 os elementos de uma sequência de acordo com uma função de seletor de chave.Groups the elements of a sequence according to a key selector function. As chaves são comparadas usando um comparador e os elementos de cada grupo são projetados usando uma função 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 os elementos de uma sequência de acordo com uma função do seletor de chave especificada e cria um valor de resultado de cada grupo e sua chave.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 os elementos de uma sequência de acordo com uma função do seletor de chave especificada e cria um valor de resultado de cada grupo e sua chave.Groups the elements of a sequence according to a specified key selector function and creates a result value from each group and its key. As chaves são comparadas usando um 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 os elementos de uma sequência de acordo com uma função do seletor de chave especificada e cria um valor de resultado de cada grupo e sua chave.Groups the elements of a sequence according to a specified key selector function and creates a result value from each group and its key. Os elementos de cada grupo são projetados usando uma função especificada.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 os elementos de uma sequência de acordo com uma função do seletor de chave especificada e cria um valor de resultado de cada grupo e sua chave.Groups the elements of a sequence according to a specified key selector function and creates a result value from each group and its key. Os valores da chave são comparados usando um comparador especificado e os elementos de cada grupo são projetados usando uma função 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>) |
Correlaciona os elementos de duas sequências com base na igualdade de chaves e agrupa os resultados.Correlates the elements of two sequences based on equality of keys and groups the results. O comparador de igualdade padrão é usado para comparar chaves.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>) |
Correlaciona os elementos de duas sequências com base na igualdade de chaves e agrupa os resultados.Correlates the elements of two sequences based on key equality and groups the results. Um IEqualityComparer<T> especificado é usado para comparar chaves.A specified IEqualityComparer<T> is used to compare keys. |
| Intersect<TSource>(IEnumerable<TSource>, IEnumerable<TSource>) |
Produz a interseção de conjunto de duas sequências usando o comparador de igualdade padrão para comparar os 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>) |
Produz a interseção de conjunto de duas sequências usando o IEqualityComparer<T> especificado para comparar os 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>) |
Correlaciona os elementos de duas sequências com base em chaves de correspondência.Correlates the elements of two sequences based on matching keys. O comparador de igualdade padrão é usado para comparar chaves.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>) |
Correlaciona os elementos de duas sequências com base em chaves de correspondência.Correlates the elements of two sequences based on matching keys. Um IEqualityComparer<T> especificado é usado para comparar chaves.A specified IEqualityComparer<T> is used to compare keys. |
| Last<TSource>(IEnumerable<TSource>) |
Retorna o último elemento de uma sequência.Returns the last element of a sequence. |
| Last<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) |
Retorna o último elemento de uma sequência que satisfaz uma condição especificada.Returns the last element of a sequence that satisfies a specified condition. |
| LastOrDefault<TSource>(IEnumerable<TSource>) |
Retorna o último elemento de uma sequência ou um valor padrão se a sequência não contém 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>) |
Retorna o último elemento de uma sequência que satisfaz uma condição ou um valor padrão, caso esse elemento não seja encontrado.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>) |
Retorna um Int64 que representa o número total de elementos em uma sequência.Returns an Int64 that represents the total number of elements in a sequence. |
| LongCount<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) |
Retorna um Int64 que representa quantos elementos na sequência atendem a uma condição.Returns an Int64 that represents how many elements in a sequence satisfy a condition. |
| Max<TSource>(IEnumerable<TSource>) |
Retorna o valor máximo em uma sequência genérica.Returns the maximum value in a generic sequence. |
| Max<TSource>(IEnumerable<TSource>, Func<TSource,Decimal>) |
Invoca uma função de transformação em cada elemento de uma sequência e retorna o 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 uma função de transformação em cada elemento de uma sequência e retorna o 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 uma função de transformação em cada elemento de uma sequência e retorna o 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 uma função de transformação em cada elemento de uma sequência e retorna o 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 uma função de transformação em cada elemento de uma sequência e retorna o valor Decimal máximo que permite valor nulo.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 uma função de transformação em cada elemento de uma sequência e retorna o valor Double máximo que permite valor nulo.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 uma função de transformação em cada elemento de uma sequência e retorna o valor Int32 máximo que permite valor nulo.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 uma função de transformação em cada elemento de uma sequência e retorna o valor Int64 máximo que permite valor nulo.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 uma função de transformação em cada elemento de uma sequência e retorna o valor Single máximo que permite valor nulo.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 uma função de transformação em cada elemento de uma sequência e retorna o 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 uma função de transformação em cada elemento de uma sequência genérica e retorna o maior valor resultante.Invokes a transform function on each element of a generic sequence and returns the maximum resulting value. |
| Min<TSource>(IEnumerable<TSource>) |
Retorna o valor mínimo em uma sequência genérica.Returns the minimum value in a generic sequence. |
| Min<TSource>(IEnumerable<TSource>, Func<TSource,Decimal>) |
Invoca uma função de transformação em cada elemento de uma sequência e retorna o 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 uma função de transformação em cada elemento de uma sequência e retorna o 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 uma função de transformação em cada elemento de uma sequência e retorna o 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 uma função de transformação em cada elemento de uma sequência e retorna o 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 uma função de transformação em cada elemento de uma sequência e retorna o valor Decimal mínimo que permite valor nulo.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 uma função de transformação em cada elemento de uma sequência e retorna o valor Double mínimo que permite valor nulo.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 uma função de transformação em cada elemento de uma sequência e retorna o valor Int32 mínimo que permite valor nulo.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 uma função de transformação em cada elemento de uma sequência e retorna o valor Int64 mínimo que permite valor nulo.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 uma função de transformação em cada elemento de uma sequência e retorna o valor Single mínimo que permite valor nulo.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 uma função de transformação em cada elemento de uma sequência e retorna o 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 uma função de transformação em cada elemento de uma sequência genérica e retorna o menor valor resultante.Invokes a transform function on each element of a generic sequence and returns the minimum resulting value. |
| OfType<TResult>(IEnumerable) |
Filtra os elementos de um IEnumerable com base em um tipo especificado.Filters the elements of an IEnumerable based on a specified type. |
| OrderBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>) |
Classifica os elementos de uma sequência em ordem crescente de acordo com uma chave.Sorts the elements of a sequence in ascending order according to a key. |
| OrderBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>, IComparer<TKey>) |
Classifica os elementos de uma sequência em ordem crescente usando um comparador especificado.Sorts the elements of a sequence in ascending order by using a specified comparer. |
| OrderByDescending<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>) |
Classifica os elementos de uma sequência em ordem decrescente de acordo com uma chave.Sorts the elements of a sequence in descending order according to a key. |
| OrderByDescending<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>, IComparer<TKey>) |
Classifica os elementos de uma sequência em ordem decrescente usando um comparador especificado.Sorts the elements of a sequence in descending order by using a specified comparer. |
| Prepend<TSource>(IEnumerable<TSource>, TSource) |
Adiciona um valor ao início da sequência.Adds a value to the beginning of the sequence. |
| Reverse<TSource>(IEnumerable<TSource>) |
Inverte a ordem dos elementos em uma sequência.Inverts the order of the elements in a sequence. |
| Select<TSource,TResult>(IEnumerable<TSource>, Func<TSource,TResult>) |
Projeta cada elemento de uma sequência em um novo formulário.Projects each element of a sequence into a new form. |
| Select<TSource,TResult>(IEnumerable<TSource>, Func<TSource,Int32,TResult>) |
Projeta cada elemento de uma sequência em um novo formulário, incorporando o índice do 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>>) |
Projeta cada elemento de uma sequência em um IEnumerable<T> e nivela as sequências resultantes em uma sequência.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>>) |
Projeta cada elemento de uma sequência em um IEnumerable<T> e nivela as sequências resultantes em uma sequência.Projects each element of a sequence to an IEnumerable<T>, and flattens the resulting sequences into one sequence. O índice de cada elemento de origem é usado no formulário projetado desse 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>) |
Projeta cada elemento de uma sequência em um IEnumerable<T>, mescla as sequências resultantes em uma sequência e chama uma função de seletor de resultado em cada elemento contido nele.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>) |
Projeta cada elemento de uma sequência em um IEnumerable<T>, mescla as sequências resultantes em uma sequência e chama uma função de seletor de resultado em cada elemento contido nele.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. O índice de cada elemento de origem é usado no formulário projetado intermediário do elemento.The index of each source element is used in the intermediate projected form of that element. |
| SequenceEqual<TSource>(IEnumerable<TSource>, IEnumerable<TSource>) |
Determina se duas sequências são iguais comparando os elementos usando o comparador de igualdade padrão para o 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 se duas sequências são iguais, comparando seus elementos usando um IEqualityComparer<T> especificado.Determines whether two sequences are equal by comparing their elements by using a specified IEqualityComparer<T>. |
| Single<TSource>(IEnumerable<TSource>) |
Retornará o único elemento de uma sequência e lançará uma exceção se não houver exatamente um elemento na sequência.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>) |
Retorna o único elemento de uma sequência que satisfaz uma condição especificada e gera uma exceção se houver mais de um tal elemento.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>) |
Retorna o único elemento de uma sequência ou um valor padrão se a sequência é vazia; esse método gera uma exceção se há mais de um elemento na sequência.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>) |
Retorna o único elemento de uma sequência que satisfaz uma condição especificada ou um valor padrão se esse elemento não existir. Esse método lança uma exceção se mais de um elemento satisfizer a condição.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) |
Ignora um número especificado de elementos em uma sequência e retorna os elementos restantes.Bypasses a specified number of elements in a sequence and then returns the remaining elements. |
| SkipLast<TSource>(IEnumerable<TSource>, Int32) |
Retorna uma nova coleção enumerável que contém os elementos de |
| SkipWhile<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) |
Ignora elementos em uma sequência, contanto que uma condição especificada seja verdadeira e retorne os 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>) |
Ignora elementos em uma sequência, contanto que uma condição especificada seja verdadeira e retorne os elementos restantes.Bypasses elements in a sequence as long as a specified condition is true and then returns the remaining elements. O índice do elemento é usado na lógica da função de predicado.The element's index is used in the logic of the predicate function. |
| Sum<TSource>(IEnumerable<TSource>, Func<TSource,Decimal>) |
Calcula a soma da sequência de valores Decimal obtidos pela invocação de uma função de transformação em cada elemento da sequência 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 a soma da sequência de valores Double obtidos pela invocação de uma função de transformação em cada elemento da sequência 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 a soma da sequência de valores Int32 obtidos pela invocação de uma função de transformação em cada elemento da sequência 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 a soma da sequência de valores Int64 obtidos pela invocação de uma função de transformação em cada elemento da sequência 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 a soma da sequência de valores Decimal anuláveis obtidos pela invocação de uma função de transformação em cada elemento da sequência 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 a soma da sequência de valores Double anuláveis obtidos pela invocação de uma função de transformação em cada elemento da sequência 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 a soma da sequência de valores Int32 anuláveis obtidos pela invocação de uma função de transformação em cada elemento da sequência 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 a soma da sequência de valores Int64 anuláveis obtidos pela invocação de uma função de transformação em cada elemento da sequência 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 a soma da sequência de valores Single anuláveis obtidos pela invocação de uma função de transformação em cada elemento da sequência 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 a soma da sequência de valores Single obtidos pela invocação de uma função de transformação em cada elemento da sequência 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) |
Retorna um número especificado de elementos contíguos do início de uma sequência.Returns a specified number of contiguous elements from the start of a sequence. |
| TakeLast<TSource>(IEnumerable<TSource>, Int32) |
Retorna uma nova coleção enumerável que contém os últimos elementos de |
| TakeWhile<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) |
Retorna os elementos de uma sequência contanto que uma condição especificada seja verdadeira.Returns elements from a sequence as long as a specified condition is true. |
| TakeWhile<TSource>(IEnumerable<TSource>, Func<TSource,Int32,Boolean>) |
Retorna os elementos de uma sequência contanto que uma condição especificada seja verdadeira.Returns elements from a sequence as long as a specified condition is true. O índice do elemento é usado na lógica da função de predicado.The element's index is used in the logic of the predicate function. |
| ToArray<TSource>(IEnumerable<TSource>) |
Cria uma matriz de um IEnumerable<T>.Creates an array from a IEnumerable<T>. |
| ToDictionary<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>) |
Cria um Dictionary<TKey,TValue> de um IEnumerable<T>, de acordo com uma função de seletor de chave 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>) |
Cria um Dictionary<TKey,TValue> de um IEnumerable<T>, de acordo com uma função de seletor de chave especificada e um comparador de chaves.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>) |
Cria um Dictionary<TKey,TValue> de um IEnumerable<T>, de acordo com as funções especificadas de seletor de chave e seletor de elemento.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>) |
Cria um Dictionary<TKey,TValue> de um IEnumerable<T> de acordo com uma função de seletor de chave, um comparador e uma função de seletor de elemento especificados.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>) |
Cria um HashSet<T> de um IEnumerable<T>.Creates a HashSet<T> from an IEnumerable<T>. |
| ToHashSet<TSource>(IEnumerable<TSource>, IEqualityComparer<TSource>) |
Cria um HashSet<T> de um IEnumerable<T> usando o |
| ToList<TSource>(IEnumerable<TSource>) |
Cria um List<T> de um IEnumerable<T>.Creates a List<T> from an IEnumerable<T>. |
| ToLookup<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>) |
Cria um Lookup<TKey,TElement> de um IEnumerable<T>, de acordo com uma função de seletor de chave 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>) |
Cria um Lookup<TKey,TElement> de um IEnumerable<T>, de acordo com uma função de seletor de chave especificada e um comparador de chaves.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>) |
Cria um Lookup<TKey,TElement> de um IEnumerable<T>, de acordo com as funções especificadas de seletor de chave e seletor de elemento.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>) |
Cria um Lookup<TKey,TElement> de um IEnumerable<T> de acordo com uma função de seletor de chave, um comparador e uma função de seletor de elemento 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>) |
Produz a união de conjunto de duas sequências usando o comparador de igualdade padrão.Produces the set union of two sequences by using the default equality comparer. |
| Union<TSource>(IEnumerable<TSource>, IEnumerable<TSource>, IEqualityComparer<TSource>) |
Produz a união de conjunto de duas sequências usando o IEqualityComparer<T> especificado.Produces the set union of two sequences by using a specified IEqualityComparer<T>. |
| Where<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) |
Filtra uma sequência de valores com base em um predicado.Filters a sequence of values based on a predicate. |
| Where<TSource>(IEnumerable<TSource>, Func<TSource,Int32,Boolean>) |
Filtra uma sequência de valores com base em um predicado.Filters a sequence of values based on a predicate. O índice de cada elemento é usado na lógica da função de predicado.Each element's index is used in the logic of the predicate function. |
| Zip<TFirst,TSecond>(IEnumerable<TFirst>, IEnumerable<TSecond>) |
Produz uma sequência de tuplas com elementos das duas sequências 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 uma função especificada para os elementos correspondentes de duas sequências, produzindo uma sequência dos resultados.Applies a specified function to the corresponding elements of two sequences, producing a sequence of the results. |
| AsParallel(IEnumerable) |
Habilita a paralelização de uma consulta.Enables parallelization of a query. |
| AsParallel<TSource>(IEnumerable<TSource>) |
Habilita a paralelização de uma consulta.Enables parallelization of a query. |
| AsQueryable(IEnumerable) |
Converte um IEnumerable em um IQueryable.Converts an IEnumerable to an IQueryable. |
| AsQueryable<TElement>(IEnumerable<TElement>) |
Converte um IEnumerable<T> genérico em um IQueryable<T> genérico.Converts a generic IEnumerable<T> to a generic IQueryable<T>. |
| Ancestors<T>(IEnumerable<T>) |
Retorna uma coleção de elementos que contém os ancestrais de cada nó na coleção de origem.Returns a collection of elements that contains the ancestors of every node in the source collection. |
| Ancestors<T>(IEnumerable<T>, XName) |
Retorna uma coleção filtrada de elementos que contém os ancestrais de cada nó na coleção de origem.Returns a filtered collection of elements that contains the ancestors of every node in the source collection. Somente os elementos que têm um XName correspondente são incluídos na coleção.Only elements that have a matching XName are included in the collection. |
| DescendantNodes<T>(IEnumerable<T>) |
Retorna uma coleção dos nós descendentes de todos os documentos e elementos na coleção de origem.Returns a collection of the descendant nodes of every document and element in the source collection. |
| Descendants<T>(IEnumerable<T>) |
Retorna uma coleção de elementos que contém os elementos descendentes de cada elemento e o documento na coleção de origem.Returns a collection of elements that contains the descendant elements of every element and document in the source collection. |
| Descendants<T>(IEnumerable<T>, XName) |
Retorna uma coleção filtrada de elementos que contém os elementos descendentes de cada elemento e o documento na coleção de origem.Returns a filtered collection of elements that contains the descendant elements of every element and document in the source collection. Somente os elementos que têm um XName correspondente são incluídos na coleção.Only elements that have a matching XName are included in the collection. |
| Elements<T>(IEnumerable<T>) |
Retorna uma coleção dos filhos elementos de cada elemento e o documento na coleção de origem.Returns a collection of the child elements of every element and document in the source collection. |
| Elements<T>(IEnumerable<T>, XName) |
Retorna uma coleção filtrada dos elementos filho de cada elemento e documento na coleção de origem.Returns a filtered collection of the child elements of every element and document in the source collection. Somente os elementos que têm um XName correspondente são incluídos na coleção.Only elements that have a matching XName are included in the collection. |
| InDocumentOrder<T>(IEnumerable<T>) |
Retorna uma coleção de nós que contém todos os nós na coleção de origem, classificados em ordem segundo o documento.Returns a collection of nodes that contains all nodes in the source collection, sorted in document order. |
| Nodes<T>(IEnumerable<T>) |
Retorna uma coleção dos nós filhos de todos os documentos e elementos na coleção de origem.Returns a collection of the child nodes of every document and element in the source collection. |
| Remove<T>(IEnumerable<T>) |
Remove todos os nós na coleção de origem do respectivo nó pai.Removes every node in the source collection from its parent node. |