Replace Nested Loops with SelectMany()
Instead of using nested foreach loops to flatten collections, SelectMany() provides a more readable and efficient way to achieve the same result. It flattens nested collections into a single sequence.
var categories = new List < List < string >> {
new List < string > {
"Apple",
"Banana"
},
new List < string > {
"Orange",
"Grape"
},
new List < string > {
"Mango"
}
};
// Flatten nested lists using SelectMany()
var flattened = categories.SelectMany(category => category).ToList();
Console.WriteLine(string.Join(", ", flattened));
//Apple, Banana, Orange, Grape, Mango