本文将介绍Linq中的Where与SkipWhile的用法,有时我们容易混淆它们。下面来看一个简单的UnitTest:
[TestMethod] public void TestSkipWhileAndWhereLinq() { //arrange string[] names = { "Jalpesh", "Jayesh", "Tushar", "Tejas", "Sanjay", "Nijesh", "Jemit", "Jay" }; var skipWhileResult = names.SkipWhile(s => s.ToLower().StartsWith("j")); //assert var expectArray=new string[] {"Tushar", "Tejas", "Sanjay", "Nijesh", "Jemit", "Jay" }; CollectionAssert.AreEqual( expectArray, skipWhileResult.ToArray()); var whereReuslt = names.Where(s => !s.ToLower().StartsWith("j")); //assert var expectArray2 = new string[] { "Tushar", "Tejas", "Sanjay", "Nijesh" }; CollectionAssert.AreEqual(expectArray2, whereReuslt.ToArray()); }
SkipWhile只是匹配一开始满足条件的元素。上面的代码一看就明白。更加请参照MSDN
SkipWhile是这样的实现的:
public static IEnumerable<TSource> SkipWhile<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) { if (source == null) throw Error.ArgumentNull("source"); if (predicate == null) throw Error.ArgumentNull("predicate"); return SkipWhileIterator<TSource>(source, predicate); } private static IEnumerable<TSource> SkipWhileIterator<TSource>(IEnumerable<TSource> source, Func<TSource, bool> predicate) { bool iteratorVariable0 = false; foreach (TSource iteratorVariable1 in source) { if (!iteratorVariable0 && !predicate(iteratorVariable1)) iteratorVariable0 = true; if (iteratorVariable0) { yield return iteratorVariable1; } } }
希望对您开发有帮助。
作者:Petter Liu
出处:http://www.cnblogs.com/wintersun/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
该文章也同时发布在我的独立博客中-Petter Liu Blog。