tags:

views:

812

answers:

3

Hello,

Is there a way without looping all the IEnumerable to get back the data inside the object (that inherited BindingList)?

MyListObject--> Transformed with Linq --> Back the data inside MyListObject

I know that I can do .ToList but it doesn't do what I would like.

Any idea? Thank :)

+1  A: 

Most lists accept a range of objects in the constructor. Will that work?

Dim objects = 'Linq statement returning IEnumberable array.
Dim mlo As New MyListObject(objects)
CStick
Unfortunately, BindingList<T> only accepts IList<T> in its constructor and not IEnumerable<T>.
LukeH
+2  A: 

One option is to wrap the returned IEnumerable into your collection type by using/adding constructor that takes IEnumerable as CStick suggest. Perhaps a bit more ellegant way is to add an extension method for the IEnumerable type that would return your collection:

static MyListObject ToMyList(this IEnumerable<T> en) {
  // construct your MyListObject from 'en' somehow
}


// And then just write:
var mylist = (from c in ... ).ToMyList()

The last option that's probably too complicated for this simple scenario is to implement all the LINQ query operators for your type (extension methods Where, Select, and many many others). The plus thing is that you could (maybe) do some things more efficiently, but it's really a bit difficult thing to do.

Tomas Petricek
I do not get what you mean by "from 'en' somehow"
Daok
ok I just see that it's your variable name :P I'll take a look, it's a little of what I would have like to avoid to do the loop manually. But well, if it's the only way...
Daok
+1 for the idea, thx
Daok
+2  A: 

I'm not sure exactly what your requirements are, especially the bit about ToList not doing what you need.

Unfortunately, BindingList<T> only accepts an IList<T> parameter in its constructor and not an IEnumerable<T>.

However, if you implement a pass-through constructor on your custom collection (or if it already has a constructor that takes IList<T>) then you could do something similar to this:

public class MyListObject<T> : BindingList<T>
{
    public MyListObject() : base() { }
    public MyListObject(IList<T> list) : base(list) { }
}

// ...

MyListObject<int> yourList = new MyListObject<int> { 1, 2, 3, 4, 5 };
yourList = new MyListObject<int>(yourList.Select(s => s * 2).ToList());
// yourList now contains 2, 4, 6, 8, 10
LukeH
This is what I would have been using without asking the question here. I asked to be sure that Linq doesn't have something that I haven't see. But well :) Thx for the input. +1 and the answer.
Daok