Last active
August 29, 2015 14:07
-
-
Save masaru-b-cl/23d08d9052379a4cf028 to your computer and use it in GitHub Desktop.
条件に合致するものを区間ごとにまとめて返す
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Linq; | |
| using System.Collections.Generic; | |
| using Microsoft.VisualStudio.TestTools.UnitTesting; | |
| namespace BufferWithPredicate | |
| { | |
| public static class EnumerableExtensions | |
| { | |
| public static IEnumerable<T[]> Buffer<T>( | |
| this IEnumerable<T> source, | |
| Func<T, bool> pred | |
| ) | |
| { | |
| var buffer = new List<T>(); | |
| foreach (var x in source) | |
| { | |
| if (pred(x)) | |
| { | |
| buffer.Add(x); | |
| } | |
| else | |
| { | |
| if (buffer.Count > 0) | |
| { | |
| yield return buffer.ToArray(); | |
| buffer.Clear(); | |
| } | |
| } | |
| } | |
| if (buffer.Count > 0) | |
| { | |
| yield return buffer.ToArray(); | |
| } | |
| } | |
| } | |
| [TestClass] | |
| public class BufferWithPredicate | |
| { | |
| [TestMethod] | |
| public void 条件がfalseなら空() | |
| { | |
| var source = new[] { 1 }; | |
| var result = source.Buffer(n => false); | |
| Assert.AreEqual(false, result.Any()); | |
| } | |
| [TestMethod] | |
| public void 結果の組を分けてくるんで返す() | |
| { | |
| var source = new[] { 2, 3, 1, 4, 5 }; | |
| var result = source.Buffer(n => n > 1).ToArray(); | |
| var first = result[0].ToArray(); | |
| Assert.AreEqual(2, first[0]); | |
| Assert.AreEqual(3, first[1]); | |
| var second = result[1].ToArray(); | |
| Assert.AreEqual(4, second[0]); | |
| Assert.AreEqual(5, second[1]); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment