Click here to Skip to main content
15,886,110 members
Articles / Programming Languages / C# 4.0

The List Trifecta, Part 2

Rate me:
Please Sign up or sign in to vote.
5.00/5 (4 votes)
7 Sep 2013LGPL310 min read 28.6K   317   12  
The BDictionary is like a Dictionary mashed up with List<T>. BList and BMultiMap also say hello.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Loyc.Collections;
using Loyc.Collections.Impl;

namespace Loyc.Collections
{
	/// <summary>This class wraps an <see cref="IEnumerator{T}"/> or 
	/// <see cref="IEnumerable{T}"/> into an <see cref="IListSource"/>, lazily 
	/// reading the sequence as <see cref="TryGet"/> is called.</summary>
	/// <remarks>Avoid calling <see cref="Count"/> if you actually want laziness;
	/// this property must read and buffer the entire sequence.</remarks>
	public class BufferedSequence<T> : ListSourceBase<T>
	{
		InternalList<T> _buffer = InternalList<T>.Empty;
		IEnumerator<T> _e; // set to null when ended

		public BufferedSequence(IEnumerable<T> e) : this(e.GetEnumerator()) { }
		public BufferedSequence(IEnumerator<T> e) { _e = e; }
	
		public override T TryGet(int index, ref bool fail)
		{
			if ((uint)index < (uint)_buffer.Count)
				return _buffer[index];
			else if (index >= 0 && _e != null) {
				while (_e.MoveNext()) {
					_buffer.Add(_e.Current);
					if (index < _buffer.Count)
						return _buffer[index];
				}
				_e = null;
			}
			fail = true;
			return default(T);
		}

		public override int Count
		{
			get {
				if (_e != null) {
					bool _ = false;
					TryGet(int.MaxValue, ref _);
				}
				return _buffer.Count;
			}
		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The GNU Lesser General Public License (LGPLv3)


Written By
Software Developer None
Canada Canada
Since I started programming when I was 11, I wrote the SNES emulator "SNEqr", the FastNav mapping component, the Enhanced C# programming language (in progress), the parser generator LLLPG, and LES, a syntax to help you start building programming languages, DSLs or build systems.

My overall focus is on the Language of your choice (Loyc) initiative, which is about investigating ways to improve interoperability between programming languages and putting more power in the hands of developers. I'm also seeking employment.

Comments and Discussions