Today I needed to do a simple thing: Combine selected values of .NET CheckListBox control into a comma separated string. I am lazy, so I decided to Google for a ready-to-use piece of code. Sure enough there’re tons of those. But all of them involve looping through control items, checking IF item is selected, then adding values.. Boring, routine stuff.
People! We live in the 21st century, age of inspiration! Uhm.. sorry, got carried away. Bottom line: I didn’t like any of those solutions and being a fan of LINQ I put together one of my own.
Let’s say I have a nice little CheckListBox like this (guess what I used to be long ago? Hint: it rhymes with Techie)
It’s very easy to select only checked values using LINQ, this 2-liner does it:
Dim sValues = From oItem As ListItem In xchkList.Items _ Where oItem.Selected Select oItem.Value
But it produces an IENumerable(of String):
What we need is a comma separated string. And this can be achieved using LINQ aggregates. Add 3 lines to the code above:
Dim sValues = _ (From oItem As ListItem In xchkList.Items _ Where oItem.Selected Select oItem.Value). _ Aggregate(Of StringBuilder)(New StringBuilder, _ Function(Current As StringBuilder, sValue As String) _ Current.AppendFormat(",{0}", sValue)).ToString.Substring(1)
And the result is desired string: