From d3388ac3df96cc6f3f06a64711439a08625cc5ad Mon Sep 17 00:00:00 2001 From: "Benjamin S. Berman" Date: Thu, 11 Feb 2016 17:28:04 -0800 Subject: [PATCH] Add find syntax --- LiveData/Collection.cs | 30 +++++++++++++++++++++++++++++- LiveData/Cursor.cs | 31 ++++++++++++++++++++++++++++--- 2 files changed, 57 insertions(+), 4 deletions(-) diff --git a/LiveData/Collection.cs b/LiveData/Collection.cs index c4e10e1..f2e5cc4 100644 --- a/LiveData/Collection.cs +++ b/LiveData/Collection.cs @@ -121,7 +121,6 @@ public Collection (string name) : base () throw new ArgumentException (string.Format ("A collection with name {0} already exists", name)); } - Collection.Create (name, instance: this); } @@ -130,6 +129,35 @@ public Cursor Find (Func selector = null) return new Cursor (collection: this, selector: selector); } + public Cursor Find (string id) + { + return new Cursor (collection: this, id: id); + } + + public Cursor Find (IEnumerable ids) + { + return new Cursor (collection: this, ids: ids); + } + + public TRecordType FindOne (string id) + { + return this [id]; + } + + public TRecordType FindOne (Func selector = null) + { + selector = selector ?? delegate(TRecordType arg) { + return true; + }; + + foreach (var record in this) { + if (selector (record)) { + return record; + } + } + return null; + } + public static Collection Create (string name) { return Create (name, new Collection ()); diff --git a/LiveData/Cursor.cs b/LiveData/Cursor.cs index 4fa87cb..18a3355 100644 --- a/LiveData/Cursor.cs +++ b/LiveData/Cursor.cs @@ -11,6 +11,7 @@ namespace Meteor public class Cursor where TRecordType : MongoDocument, new() { + public Collection collection { get; protected set; @@ -21,12 +22,29 @@ public Func selector { protected set; } + public IEnumerable ids { + get; + protected set; + } + public Cursor (Collection collection, Func selector = null) { this.collection = collection; this.selector = selector ?? SelectAll; } + public Cursor (Collection collection, string id) + { + this.collection = collection; + this.ids = new string[] { id }; + } + + public Cursor (Collection collection, IEnumerable ids) + { + this.collection = collection; + this.ids = ids; + } + public Observe Observe (Action added = null, Action changed = null, Action removed = null) { return new Observe (collection: this.collection, added: added, changed: changed, removed: removed, selector: selector); @@ -34,10 +52,17 @@ public Observe Observe (Action added = null, Ac public IEnumerable Fetch () { - foreach (var record in collection) { - if (selector (record)) { - yield return record; + if (ids == null) { + foreach (var record in collection) { + if (selector (record)) { + yield return record; + } } + yield break; + } + + foreach (var id in ids) { + yield return collection [id]; } yield break;