Ok, en su ejemplo que estés efectivamente acaba de encontrar la entrada para el objeto Customer
con Id
= 1 y la actualización del valor asociado. En la práctica, creo que su código probablemente podrá obtener una referencia a su objeto previsto Customer
antes de actualizar el valor asociado en el diccionario. Si ese es el caso, entonces no hay necesidad de un bucle.
A continuación se muestra un ejemplo muy simple en el que no se necesita un bucle porque su código ya tiene una referencia a la variable customer1
. Si bien mi ejemplo es demasiado simplificado, el concepto es que podría obtener una referencia al objeto Customer
deseado a través de otros medios que no sean iterar sobre el diccionario.
static void Main(string[] args)
{
Dictionary<Customer, int> CustomerOrderDictionary = new Dictionary<Customer, int>();
Customer customer1 = new Customer { Id = 1, FullName = "Jo Bloogs" };
Customer customer2 = new Customer { Id = 2, FullName = "Rob Smith" };
CustomerOrderDictionary.Add(customer1, 3);
CustomerOrderDictionary.Add(customer2, 5);
// you already have a reference to customer1, so just use the accessor on the dictionary to update the value
CustomerOrderDictionary[customer1]++;
}
Si es necesario realizar algún tipo de actualización de múltiples Customer
objetos basados en otros criterios, entonces puede que tenga un bucle. El siguiente ejemplo asume que tendrá alguna colección que no sea el diccionario que almacena sus objetos Customer
, y que puede usar esa colección de objetos Customer
para identificar aquellos cuyo valor asociado en el diccionario debe actualizarse.
static void Main(string[] args)
{
// presumably you will have a separate collection of all your Customer objects somewhere
List<Customer> customers = new List<Customer>();
Customer customer1 = new Customer { Id = 1, FullName = "Jo Bloogs" };
Customer customer2 = new Customer { Id = 2, FullName = "Rob Smith" };
Customer customer3 = new Customer { Id = 3, FullName = "Rob Zombie" };
customers.Add(customer1);
customers.Add(customer2);
customers.Add(customer3);
Dictionary<Customer, int> CustomerOrderDictionary = new Dictionary<Customer, int>();
CustomerOrderDictionary.Add(customer1, 3);
CustomerOrderDictionary.Add(customer2, 5);
// let's just say that we're going to update the value for any customers whose name starts with "Rob"
// use the separate list of Customer objects for the iteration,
// because you would not be allowed to modify the dictionary if you iterate over the dictionary directly
foreach (var customer in customers.Where(c => c.FullName.StartsWith("Rob")))
{
// the dictionary may or may not contain an entry for every Customer in the list, so use TryGetValue
int value;
if (CustomerOrderDictionary.TryGetValue(customer, out value))
// if an entry is found for this customer, then increment the value of that entry by 1
CustomerOrderDictionary[customer] = value + 1;
else
// if there is no entry in the dictionary for this Customer, let's add one just for the heck of it
CustomerOrderDictionary.Add(customer, 1);
}
}
Si este no es el caso y la única fuente de Customer
objetos que usted tiene disponible es el diccionario en sí, entonces usted tendrá que realizar algún tipo de clonación/copia de esos objetos a una lista separada/matriz antes de iterar sobre el diccionario para la modificación. Ver la respuesta de Jon Skeet para este caso; sugiere utilizar un filtro Where
en la propiedad Keys
del diccionario y usa el método ToList
para crear una instancia List<Customer>
por separado a los efectos de la iteración.
Hola, muchas gracias que funcionó. Trataré de ver si eso funciona con el código real. Gracias – user9969