For each use of linq, how to use else

I have code that checks certain files, and then, if the condition is met, it goes to stats.matching .... I use this for every linq:

  For Each file As String In From file1 In Stats.FoundFiles 
                             Let ftpFile = Utils.ToLowerWithoutSpaces(file1) 
                             Where ftpFile.Contains(currentReportName) 
                             Select file1
      Stats.MatchingFiles.Add(file)
  Next

The question is how to implement it here yet.

+4
source share
2 answers

So, you want to fill another collection with files that do not contain a word.

Dim matching = From file1 In Stats.FoundFiles 
               Let ftpFile = Utils.ToLowerWithoutSpaces(file1) 
               Where ftpFile.Contains(currentReportName)
Dim mismatching = From file1 In Stats.FoundFiles 
                  Let ftpFile = Utils.ToLowerWithoutSpaces(file1) 
                  Where Not ftpFile.Contains(currentReportName)

For Each file As String In matching 
    Stats.MatchingFiles.Add(file)
Next
For Each file As String In mismatching 
    Stats.MismatchingFiles.Add(file)
Next

This is a simple solution, you can also use Exceptwhich is more efficient:

Dim mismatching = Stats.FoundFiles.Except(matching)
+3
source

I think in your case the original loop For Eachwith If... Elsewould be a fairly simple approach
And loop a Stats.FoundFileonly once

For Each file As String In Stats.FoundFiles 
    Dim ftpFile As String = Utils.ToLowerWithoutSpaces(file) 
    If ftpFile.Contains(currentReportName) = True Then
        Stats.MatchingFiles.Add(file)
    Else
        Stats.MismatchingFiles.Add(file)
    End If
Next

Or, if you are a LINQ fan and should use it, you can play with Aggregatethe extension method

Stats.FoundFiles.Aggregate(String.Empty, 
                           Function(seed, file)                                   
                               If Utils.ToLowerWithoutSpaces(file).Contains(file) Then
                                   Stats.MatchingFiles.Add(file)
                               Else
                                   Stats.MismatchingFiles.Add(file)
                               End If
                               Return String.Empty
                           End Function)
0
source

All Articles