smack
Junior Member
- Feb 1, 2010
- 182
- 80
Environment: Visual Studios 2008 using VB
(this is also valid for c# although the syntax is slightly different)
i just learned a nifty technique that you can apply to working with collections and lists. this is kind of an extension of the linq concept, it uses predicates and lambdas to accomplish what you want. this can be used with several different methods associated with lists and collections, i specifically needed this for a remove all. i'm using a list of integers for simplicity, but this applies to properties and values for any class or object.
in c# you can use anonymous delegates in addition to lambdas (in vb you need explicit delegates).
here is a slightly different example using the properties of a user defined class:
along with RemoveAll here is a short list of some of the other methods this works with:
TrueForAll
Find
FindLast
FindAll
etc...
some related links:
just thought this was cool and wanted to share it, this may be one of those things where once again i am the last one to learn about it.
(this is also valid for c# although the syntax is slightly different)
i just learned a nifty technique that you can apply to working with collections and lists. this is kind of an extension of the linq concept, it uses predicates and lambdas to accomplish what you want. this can be used with several different methods associated with lists and collections, i specifically needed this for a remove all. i'm using a list of integers for simplicity, but this applies to properties and values for any class or object.
in c# you can use anonymous delegates in addition to lambdas (in vb you need explicit delegates).
Code:
[SIZE=2]Dim theList As New List(Of Integer)[/SIZE]
[SIZE=2]theList.Add(1)[/SIZE]
[SIZE=2]theList.Add(2)[/SIZE]
[SIZE=2]theList.Add(3)[/SIZE]
[SIZE=2]theList.Add(4)[/SIZE]
[SIZE=2]theList.Add(5)[/SIZE]
[SIZE=2]theList.Add(3)[/SIZE]
[SIZE=2]theList.Add(3)[/SIZE]
[SIZE=2]theList.Add(3)[/SIZE]
[SIZE=2]Debug.WriteLine("Pre-Count: " & theList.Count.ToString())[/SIZE]
[SIZE=2]' witchcraft![/SIZE]
[SIZE=2]theList.RemoveAll(Function(a) a = 3)[/SIZE]
[SIZE=2]Debug.WriteLine("Post-Count: " & theList.Count.ToString())[/SIZE]
Code:
' find the object in the collection that we need.
' ToVerify is a type specific list
Current = (From x In ToVerify _
Where x.ID = 5 _
Select x).First
' set up your predicate expression with a lambda.
ToVerify.RemoveAll(Function(A) A.ID = 5)
TrueForAll
Find
FindLast
FindAll
etc...
some related links:
Code:
[SIZE=2]hxxp://bloggingabout.net/blogs/fadzai/archive/2009/10/11/predicates-and-lambda-functions-for-filtering-and-searching.aspx[/SIZE]
[SIZE=2]hxxp://stackoverflow.com/questions/59166/how-do-you-declare-a-predicate-delegate-inline[/SIZE]
[SIZE=2]hxxp://msdn.microsoft.com/en-us/library/wdka673a.aspx[/SIZE]
just thought this was cool and wanted to share it, this may be one of those things where once again i am the last one to learn about it.