linq-Count
源码:
public static int Count<TSource>(this IEnumerable<TSource> source) { if (source == null) throw Error.ArgumentNull("source"); ICollection<TSource> collectionoft = source as ICollection<TSource>; if (collectionoft != null) return collectionoft.Count; ICollection collection = source as ICollection; if (collection != null) return collection.Count; int count = 0; using (IEnumerator<TSource> e = source.GetEnumerator()) { checked { while (e.MoveNext()) count++; } } return count; } public static int Count<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) { if (source == null) throw Error.ArgumentNull("source"); if (predicate == null) throw Error.ArgumentNull("predicate"); int count = 0; foreach (TSource element in source) { checked { if (predicate(element)) count++; } } return count; }
其实这里有很多东西。等会再看。
1.先讨论下。ICollection
- 命名空间: System.Collections
- 程序集: mscorlib.dll, System.Runtime.dll
定义所有非泛型集合的大小、枚举数和同步方法
namespace System.Collections { // 摘要: // 定义所有非泛型集合的大小、枚举器和同步方法。 [ComVisible(true)] public interface ICollection : IEnumerable { // 摘要: // 获取 System.Collections.ICollection 中包含的元素数。 // // 返回结果: // System.Collections.ICollection 中包含的元素数。 int Count { get; } // // 摘要: // 获取一个值,该值指示是否同步对 System.Collections.ICollection 的访问(线程安全)。 // // 返回结果: // 如果对 System.Collections.ICollection 的访问是同步的(线程安全),则为 true;否则为 false。 bool IsSynchronized { get; } // // 摘要: // 获取一个可用于同步对 System.Collections.ICollection 的访问的对象。 // // 返回结果: // 可用于同步对 System.Collections.ICollection 的访问的对象。 object SyncRoot { get; } // 摘要: // 从特定的 System.Array 索引处开始,将 System.Collections.ICollection 的元素复制到一个 System.Array // 中。 // // 参数: // array: // 作为从 System.Collections.ICollection 复制的元素的目标位置的一维 System.Array。System.Array // 必须具有从零开始的索引。 // // index: // array 中从零开始的索引,将在此处开始复制。 // // 异常: // System.ArgumentNullException: // array 为 null。 // // System.ArgumentOutOfRangeException: // index 小于零。 // // System.ArgumentException: // array 是多维的。- 或 -源 System.Collections.ICollection 中的元素数目大于从 index 到目标 array // 末尾之间的可用空间。 // // System.ArgumentException: // 源 System.Collections.ICollection 的类型无法自动转换为目标 array 的类型。 void CopyTo(Array array, int index); } }
我在其他地方,看到一个有意思的案例01,来来来,给大家分享下。
int count = lst.Where(ch => char.IsNumber(ch)).Count();
更好是这样
int count = lst.Count(char.IsNumber);
前面那个为什么不这样
int count = lst.Where(char.IsNumber).Count();
我也不会这样写。基础弱了。。/(ㄒoㄒ)/~~
其实仔细想想,where的入参是委托。也就是可以传递一个方法。只要入参和返回值类型相同,这里是可以直接把方法名传入。
--案例02
某人想从一个字符串集合中筛选掉空行,结果写了这么一句(模拟):
string[] lst = { "\r\n", "\r\n1", "\r\n2", "\r\n3" }; var v = lst.SkipWhile(str => str.Trim() == "\r\n").ToList();
问题1:trim会移除空格
问题2:不理解SkipWhile
SkipWhile我后面会看下源码的。
还有一些也挺好
而某人使用LINQ以后,写下了这样一个:
flg = arr.Where(i => i <= 10).Count() > 0;
(大家对于=>i<=
是不是觉得挺有意思的)
当然,他肯定不知道LINQ中有Any这个方法:
flg = arr.Any(i => i <= 10);
而All与Any“相反”,可以判断数组中的值是否都小于10。