
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
320
|
Chapter 5: Collections
This recipe uses the ForEach method of a List<T> object in two different ways. The
first is to actually modify the values of each element of the
List<T> object:
// Add 2 to all Data.val integer values.
numbers.ForEach(delegate(Data obj)
{
obj.val += 2;
});
This call to ForEach will iterate over each Data element within the numbers List<Data>
object. On every iteration, the value val contained in the current Data object obj has
its value incremented by two.
The second way is to collect a total of all the values
val contained in each Data object
obj in the numbers List<Data> object:
// Total val integer values in all Data objects in the List.
int total = 0;
numbers.ForEach(delegate(Data obj)
{
total += obj.val;
});
This code uses the total variable to build a running total of the values contained in
each element. In this instance you do not modify any values in any of the
Data
objects; instead, you examine each Data object and record information about its
value.
See Also
See the “Array Class,” “List<T> Class,” and “ForEach Method” topics in the MSDN
documentation.
5.17 Creating a Read-Only Array or List<T>
Problem
You need a way to create a read-only Array or List<T>, where the Array or List<T>
itself is read-only.
Solution
Use the AsReadOnly method of the Array or List<T>