Convert Array to Generic List and find object in list

  • Thread starter Thread starter Chris Kennedy
  • Start date Start date
C

Chris Kennedy

I am getting a generic list of objects from a webservice. The list is
converted to an array by this process. How do I convert the array back to a
list and is there any way of finding an object within the list via one it's
properties. I have seen it done in C# but not VB.
E.g. obj = get object from list where obj.id = 1. I could do some kind of
solution using loops but I was hoping for something a little more slick.
This is for .net 2.0 by the way. Regards, Chris.
 
Chris said:
I am getting a generic list of objects from a webservice. The list is
converted to an array by this process. How do I convert the array back to a
list

You can pass an array (or, indeed, instance of any class that
implements IEnumerable<T>) to constructor of List<T>:

int[] ia = { 1, 2, 3 };
List<int> il = new List<int>(ia);

But you don't actually need to do that in this case; see below.
and is there any way of finding an object within the list via one it's
properties. I have seen it done in C# but not VB.

It's the same in both - you use List<T>.Find() - though VB8 (the one
that came with .NET 2.0 & VS 2005) is lengthier because it didn't have
anonymous delegates.

If what you have is an array rather than list, then you can search
that directly by using Array.Find said:
E.g. obj = get object from list where obj.id = 1. I could do some kind of
solution using loops but I was hoping for something a little more slick.
This is for .net 2.0 by the way. Regards, Chris.

Note that you can use VS2008 (and VB9) with all the new language
features, and still target 2.0. If so, you could use the VB9 syntax
for lambdas:

Dim foos As List(Of Foo)
Dim foo As Foo = foos.Find(Function(foo) foo.id = 1)

or, for arrays:

Dim foos() As Foo
Dim foo As Foo = Array.Find(foos, Function(foo) foo.id = 1)
 
Back
Top