C# 中的 SelectMany 是一個 LINQ 方法,它主要用于將多個集合或可迭代對象中的元素合并到一個序列中。這個方法可以解決以下幾種難題:
SelectMany 將這些嵌套集合扁平化為一個單一的集合。List<int> nestedList = new List<List<int>> {
new List<int> { 1, 2, 3 },
new List<int> { 4, 5, 6 },
new List<int> { 7, 8, 9 }
};
List<int> flattenedList = nestedList.SelectMany(innerList => innerList).ToList();
SelectMany。var query1 = from item in collection1 select item;
var query2 = from item in collection2 select item;
var combinedResults = query1.SelectMany(item => query2.Where(innerItem => innerItem == item));
SelectMany。var query = from item in databaseContext.Items
select new { Item = item, Category = item.Category };
var flattenedResults = query.SelectMany(x => x.Category.Items).ToList();
總之,SelectMany 是一個非常有用的方法,可以幫助你處理嵌套集合、合并多個查詢結果以及在流式處理過程中展平數據。