Arrays, Generics
Arrays are one of the many features brought with Dynamic.
The following example demonstrates how to use arrays:
As a rule of thumb: to save and restore
data use Dynamic, all other work is recommended to perform on native objects
//Create object
Dynamic datamix = new Dynamic();
datamix["Number"] = 46;
datamix["Int array"] = new
int[] { 1442, 7557, 9938, 1048, 12774, 3988,
16833, int.MaxValue, int.MinValue
};
datamix["Object array"] = new Book[] {
new
Book() { Title = "Atilla",
Parent = new ParentBook()
{ Publisher = "Hun" } },
null,
new
Book() { Title = "Gengis
Khan", Parent = new ParentBook() { Publisher = "Europe"}
}
};
//Access array
int[] intArray
= datamix["Int array"];
Assert.IsNotNull(intArray);
Dynamic[]
bookArray = datamix["Object array"];
Assert.AreEqual("Atilla", (string)bookArray[0]["Title"]);
We shall store object
before we do any Dynamic-To-Native conversions
//Before we do
any work on object we shall store the object
db.Store(datamix);
...
//Queries
var res =
db.Query<Dynamic>().Where(d => d["Int array"] == 9938).ToList<Dynamic>();
Assert.IsNotNull(res);
Assert.AreEqual(1,
res.Count);
res = (from Dynamic d in db where d["Object array"]["Parent"]["Publisher"] == "Hun"
select d).ToList<Dynamic>();
Assert.IsNotNull(res);
Assert.AreEqual(1,
res.Count);

With generics like
List<T> it is also recommended to preserve arrays.
Here is an example:
List<Book> list = new List<Book>();
list.Add(new Book() { Title = "Unseen
Academicals", Parent = new ParentBook() { Publisher = "Europe" } });
datamix["Generics"] = list.ToArray();
Just arrays.. List<T>, Dictionary<T, K> are
only syntactic sugar
//Before we do any conversion we shall store the
object
db.Store(datamix);
...
#region Add
element to existing array
//Update generics
Dynamic[] array = datamix["Generics"];
//We will work with the List<T> in our
business application - it makes life simpler
List<Dynamic> nativeList
= new List<Dynamic>(array);
//Add new book
nativeList.Add(new Dynamic(new Book() { Title = "Atilla",
Parent = new ParentBook() { Publisher = "Hun" } }));
//We store back array, since amount of elements
changed
datamix["Generics"] = nativeList.ToArray();
db.Store(datamix);
#endregion
#region Update
element in existing array
//Let's update existing book in array
array = datamix["Generics"];
nativeList = new List<Dynamic>(array);
Dynamic @do
= nativeList[0];//let's say element 0
Book book = @do.ToNative<Book>();
//Change object
book.Title = "Joel on
software";
book.Parent.Publisher = "Hun";
//Do not forget to update field, since Dynamic
does not know that book has been changed
@do.FromNative(book);
//Since arrays are referencing objects, and
array structure didn't change we can simply store updated object
db.Store(@do);
#endregion