Partilhar via


VB Expression Example: Manipulating generic lists

Let’s walk through the process of manipulating a generic list using VB expressions.

Say you have added a C# class to your C# workflow project with the following code (yes, you can still use C# for all the heavy lifting):

 public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; } 

        public Person()
        {
        } 

        public Person(string name, int age)
        {
            Name = name;
            Age = age;
        } 

        public override string ToString()
        {
            return "Name: " + this.Name + " Age: " + this.Age;
        }
    } 

Drop a Sequence into the workflow, add an Imports statement for the current project’s namespace, and build the solution before you continue. Now create a new variable in the Variable designer of type List<Person> named people. Give it the following default value:

 Nothing

(After a while you do get used to typing Nothing instead of null). OK, that was boring. Let’s initialize it with data instead using collection initialization syntax instead. Change the default value from Nothing to

 New List(Of  Person) From {New Person("Joe Test", 22), New Person("Jane Test", 35), New Person("Sally Temp", 68)} 

Now let’s check and see if a person named “Bob Test” appears in our collection. This will demonstrate the lambda syntax in VB in a LINQ extension method. Drop an If activity into your Sequence. Write the following condition:

 Not people.Exists(Function(p) p.Name="Bob Test") 

Now you can add Bob to the people collection using the InvokeMethod activity if Bob does not exist in the collection. Drop an InvokeMethod in the Then part of the If activity. Set InvokeMethod’s TargetObject property to people, set the MethodName to Add, and  through the property grid create a parameter with direction In, type Person, and value

 New Person("Bob Test", 55)

Now let’s have a second collection with some more people. Create another variable of type List<Person> named morePeople and the following default value, using the parameterless constructor this time:

 New List(Of Person) From
{New Person With {.Name = "George Test", .Age = 6},
 New Person With {.Name = "Fiona Temp", .Age = 15},
 New Person With {.Name = "Jordan Temp", .Age = 92}
}

Now let’s print the name of all of the people in both lists that are under age 30. Drop a ForEach<T> in your sequence, change T to Person, and set the values to

 From a In people.Concat(morePeople)
Where a.Age < 30
Select a 

Drop a Writeline inside the ForEach, set the Text to

 item.ToString

and you will be able to see the results of this operation. You should see the following output:

 Name: Joe Test Age: 22
Name: George Test Age: 6
Name: Fiona Temp Age: 15 

That was pretty easy. See, VB’s not so bad once you get used to it.