前言
如果在使用 LINQ 的 SelectMany 函数时遇到了空引用(null)错误,这通常是因为在源序列中存在空值。在尝试使用 SelectMany 函数之前,你可以使用 Where 函数筛选掉源序列中的空值,或者在 SelectMany 函数中添加一个 null 引用检查。以下是一个例子:
示例
List<List<int>> listOfLists = new List<List<int>> {
new List<int> { 1, 2, 3 },
null,
new List<int> { 4, 5, 6 }
};
IEnumerable<int> flattenedList = listOfLists
.Where(list => list != null) // 筛选掉空引用
.SelectMany(list => list); // 使用 SelectMany 函数展开列表
foreach (int i in flattenedList) {
Console.WriteLine(i);
}