linq-DefaultIfEmpty
源码:
public static IEnumerableDefaultIfEmpty (this IEnumerable source) { return DefaultIfEmpty(source, default(TSource)); } public static IEnumerable DefaultIfEmpty (this IEnumerable source, TSource defaultValue) { if (source == null) throw Error.ArgumentNull("source"); return DefaultIfEmptyIterator (source, defaultValue); } static IEnumerable DefaultIfEmptyIterator (IEnumerable source, TSource defaultValue) { using (IEnumerator e = source.GetEnumerator()) { if (e.MoveNext()) { do { yield return e.Current; } while (e.MoveNext()); } else { yield return defaultValue; } } }
Console.WriteLine(default(int)); // output: 0
这个也很好理解,如果对应集合没有值则返回对应类型的默认值。
int[] ss = new int[10];
var sst = ss.DefaultIfEmpty();
返回的数组元素都被初始化为0.