C # unchanged set of sets,
If an object can change its state, it is difficult to use it in multiple simultaneously running tasks. These sets must be synchronized. If the object cannot change its state, it is easy to use in multiple threads.
Microsoft provides a new Collection Library: Microsoft Immutable Collection. As the name suggests, it contains the unchanged collection classes-the collection classes that cannot be changed after creation. This class is defined in System. Collection. Immutable.
// Use the static Create method to Create the array. The Create method is overloaded and can pass any number of elements ImmutableArray <string> a1 = ImmutableArray. create <string> (); // The Add method does not change the ImmutableArray set itself, but returns a new ImmutableArray set. <string> a2 = a1.Add ("Williams "); // multiple Add methods can be called at a time. ImmutableArray <string> a3 = a2.Add ("Ferrari "). add ("Mercedes "). add ("Red Bull Racing"); foreach (var item in a3) {Console. writeLine (item );}
No complete set is copied at each stage of the unchanged array. On the contrary, the unchanged type uses the shared state and only copies the set as needed.
However, filling the set first and then converting it into an unchanged array will be more efficient (using the ToImmutableList method ). When some processing is required, it can be changed to a variable set (using the ToBuilder method ). Use ImmutableList <Account>. Builder provided by the unchanged set.
List<Account> accounts = new List<Account>() { new Account { Name = "Scrooge McDuck", Amount = 667377678765m }, new Account { Name = "Donald Duck", Amount = -200m }, new Account { Name = "Ludwig von Drake", Amount = 20000m }}; ImmutableList<Account> immutableAccounts = accounts.ToImmutableList(); ImmutableList<Account>.Builder builder = immutableAccounts.ToBuilder(); for (int i = 0; i < builder.Count; i++) { Account a = builder[i]; if (a.Amount > 0) { builder.Remove(a); } } ImmutableList<Account> overdrawnAccounts = builder.ToImmutable(); foreach (var item in overdrawnAccounts) { Console.WriteLine("{0} {1}", item.Name, item.Amount); } public class Account { public string Name { get; set; } public decimal Amount { get; set; } }
A read-only collection (http://www.cnblogs.com/afei-24/p/6824791.html) provides a read-only view of the collection. If you do not use a read-only view to access a set, the set can still be modified. And never change the set.