ConcurrentBagbag = new ConcurrentBag (); bag.Add("apple"); bag.Add("banana"); bag.Add("cherry"); bag.Add("date"); bag.Add("elderberry"); var groups = bag.GroupBy(fruit => fruit[0]); foreach (var group in groups) { Console.WriteLine("Fruits that start with the letter '{0}':", group.Key); foreach (var fruit in group) Console.WriteLine(fruit); }
ConcurrentBagIn this example, we create a ConcurrentBag of integers from 1 to 10 and add them to the bag. We then use GroupBy to group the integers based on whether they are divisible by 3 or not and iterate over the resulting groups. The ConcurrentBag and GroupBy methods are part of the System.Collections.Concurrent namespace in the .NET Framework library.bag = new ConcurrentBag (); for (int i = 1; i <= 10; i++) { bag.Add(i); } var groups = bag.GroupBy(n => n % 3 == 0 ? "divisible by 3" : "not divisible by 3"); foreach (var group in groups) { Console.WriteLine("Numbers that are {0}:", group.Key); foreach (var num in group) { Console.WriteLine(num); } }