Home > other >  Getting specific lines of data from a string
Getting specific lines of data from a string

Time:02-17

I use Mailkit and it has a function that fetch me email body text GetMessage().Textbody , i want to get specific lines of email body that contain specific strings

For example:

12313 banana milkshake
12356 choco milkshake
kiwi milkshake 1231313

and goes on....

I want to get from the 700 lines of email text body only 2 lines that contains the word "kiwi" and "choco"

   Using reader As New StreamReader("mail.txt")
                While Not reader.EndOfStream
                    Dim line As String = reader.ReadLine()
                    If line.Contains("kiwi" or "choco") Then
                        Console.WriteLine(line)
                        Exit While
                    End If
                End While
            End Using

i've been trying to find a better and faster way instead of saving string to file then using this

CodePudding user response:

in c# since I dont know vb.net but you can translate

string msg = GetMessage().TextBody();
var lines = msg.Split('\n');
var res = lines.Where(l=>(l.Contains("kiwi") || l.Contains("choco")));

if the linq stuff doesnt translate well to vb.net then do

var res = new List<string>();
foreach(var l in lines)
{
    if (l.Contains("kiwi") || l.Contains("choco"))
    {
         res.Add(l);
    }
}

CodePudding user response:

You can't use or inside the function call like that; you need two separate Contains() calls. Also, this can be way shorter:

Dim lines = File.ReadLines("mail.txt").
            Where(Function(line) line.Contains("kiwi") OrElse line.Contains("choco"))

For Each line As String In lines
    Console.WriteLine(line)
Next

But that still assumes the mail.txt file. Given a string like Textbody we can write this function:

Public Iterator Function GetLines(input As String) As IEnumerable(Of String)
    Dim line As String = Nothing
    Using rdr As New StringReader(input) ' Not StreamReader!
       While (line = rdr.ReadLine()) IsNot Nothing
            Yield line
       End While
    End Using
End Function

And then use it to replace the File.ReadLines() in my original sample like so:

Dim lines = GetLines(GetMessage().Textbody).
            Where(Function(line) line.Contains("kiwi") OrElse line.Contains("choco"))

For Each line As String In lines
    Console.WriteLine(line)
Next
  • Related