[CSHARP-210] Add ToArray and ToList methods to BsonArray Created: 22/Apr/11  Updated: 02/Apr/15  Resolved: 25/Apr/11

Status: Closed
Project: C# Driver
Component/s: Feature Request
Affects Version/s: 1.0
Fix Version/s: 1.1

Type: New Feature Priority: Minor - P4
Reporter: Robert Stam Assignee: Robert Stam
Resolution: Done Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

It would be nice if BsonArray had ToArray and ToList methods so we could write code like:

var document = new BsonDocument("array", new BsonArray

{ 1, 2, 3 }

);
var list = document["array"].AsBsonArray.ToList<int>();

instead of:

var list = document["array"].AsBsonArray.Select(v => v.AsInt32).ToList();

or something similar if there's a better alternative.



 Comments   
Comment by Robert Stam [ 25/Apr/11 ]

See previous comments regarding why ToList<T> is not really workable, but I did add a non-generic ToList method to complement the existing ToArray method.

Comment by Robert Stam [ 25/Apr/11 ]

Turns out that implementing ToList<T> has problems:

1. There is no foolproof way of converting BsonValue to <T> (conversion depends on what <T> is)
2. Casting the RawValue involves boxing: (<T>) v.RawValue and only works for some BsonValue subclasses
3. Use of <T> makes it look like any type can be used, when in fact only a limited set are valid

I see the following alternatives:

1. Leave things as they are (after all, it's only two method calls: Select and ToList)
2. Add some special methods (e.g. ToInt32List) for selected primitive types (Double, String, ObjectId, Boolean, DateTime, Int32, Int64)

Alternative 2 would add 14 new methods to the API, and I suggest that even then it's still not good enough. Each method leaves lots of room for ambiguity. Take ToInt32List for example:

1. Should it skip elements that aren't already Int32 or convert them?
2. If converting doubles to Int32 should it trunctate, round down, round up? How to handle overflow?
3. If converting Int64 to Int32 how should overflow be handled?
4. Should string be convertible to Int32 by parsing? If so, under what CultureInfo?

My conclusion is that we leave things the way they are. There's very little extra code that has to be written as is, and you have total control over how you want the conversion to be done.

NOTE: I actually did add a ToList method to complement the existing ToArray method. It returns a List<BsonValue>.

Generated at Wed Feb 07 21:36:08 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.