I need to separate a List(Of Tuple(Of String, Integer))
to get two List's(Of String)
. If the String
matching some function ValidateFormat
(returns Boolean
), then I need it in "match
" List, if not - in "notMatch
" List.
I can use Where
extension method twice to get two List's(Of Tuple, Integer):
Dim initial As List(Of Tuple(Of String, Integer))
'...initial List filled..'
Dim match As List(Of Tuple(Of String, Integer)) = _
initial.Where(Function(x) ValidateFormat(x.Item1)).ToList
Dim notMatch As List(Of Tuple(Of String, Integer)) = _
initial.Where(Function(x) Not ValidateFormat(x.Item1)).ToList
But I need just Lists of String
, not Tuple
. Is there an effective way to do this? Thanks.
I'd use something like:
var lookups = initial.ToLookup(x => ValidateFormat(x.Item1), x => x.Item2);
var match = lookups[true].ToList();
var notMatch = lookups[false].ToList();
That checks each item once, splitting the collection into groups of "matching" or "not matching" - and the second argument to ToLookup
says how to convert each original element into a value in the lookup for the specific key (the true/false in this case).
You could use Where
and Select
of course - this just feels cleaner to me.
See more on this question at Stackoverflow