Question Array.Foreach

Sreekumar

New member
Joined
Aug 19, 2011
Messages
2
Programming Experience
Beginner
Hi,
I am new to .net.
Please give me some guidance to the following problem.
I have to fill a listbox with the results avaiable by querying windows service using ServiceController.GetServices method
I will list down the code I used.
I know using foreach to fill the listbox.
But I want to use array.foreach with lambda or delegates.(inline function)
I don't have any clue.
Please helpme.
My VB.Net code

Public class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim services As ServiceProcess.ServiceController() = ServiceProcess.ServiceController.GetServices
'For Each s In services
'ListBox1.Items.Add(s.DisplayName.ToString)
'Next
' Array.ForEach(services,delegate(s as serviceprocess.servicecontroller) listbox1.items.add(s.displayname)o
Array.ForEach(services, AddressOf ListBoxAdd) -- This line I understood
'NO IDEA HOWTO USE DELEGATES OR LAMBDA
' Array.ForEach(services,delegate(s as serviceprocess.servicecontroller) listbox1.items.add(s.displayname)
End Sub
Public Sub ListBoxAdd(ByVal s As ServiceProcess.ServiceController)
ListBox1.Items.Add(s.DisplayName)
End Sub


End


Class

 
A delegate is a reference to a method. In the code you have currently, 'AddressOf ListBoxAdd' creates a delegate that refers to the ListBoxAdd method. That means that, for each element in the array, the ListBoxAdd method will be executed and the array element passed as an argument.

Now, if you're using VB 2008, you simply cannot do it any other way. There is no such thing as an anonymous method in VB as there is in C#, which is where the 'delegate' keyword is used. Lambdas are basically a replacement for anonymous methods but in VB they originally could only represent methods that return a value, i.e. Functions. You want to represent a Sub, which is not supported until VB 2010. If you are indeed using VB 2010 then it looks like this:
Array.ForEach(services, Sub(s) ListBox1.Items.Add(s.DisplayName))
In each case, the second argument to Array.ForEach is a reference to a method that takes a ServiceController as an argument.
 
I am new to vb.net and i know that control array is not available in .net, Please help me out regarding "assigning value to array from text boxes using for next loop in vb.net".
because i have to assign value to array from more than 40 textboxes and its laborious job to assign individually.
 
I am new to vb.net and i know that control array is not available in .net, Please help me out regarding "assigning value to array from text boxes using for next loop in vb.net".
because i have to assign value to array from more than 40 textboxes and its laborious job to assign individually.
Put the TextBoxes in an array and then use a For loop. Inside the loop, use the loop counter as an index into both arrays.
 
Back
Top