Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

read text file and do subtraction using C# or VB.net

Posted on 2012-04-09
4
Medium Priority
?
781 Views
Last Modified: 2012-04-09
Hello, I have provided a sub that reads a DISTINCT list of numbers line by line from a file then queries an Excel file for the matching results. This result is then writing to a second file named "C:\Queried Master Total List.txt" line by line. The output looks very much like this:

172,28
1981,36
1250,37
2717,37
1231,38
1265,38
57,39
1429,39
1992,39
1000,41
1096,41
2577,41


The problem:

I do not know how to take these results and put them in an array. I need a solution that will read these values and subtract each value from the next one(like 172-0, 1981-0, 1250-0, 2717-1250, 1231-0, 1265-1231, 57-0, 1429-57, 1992-1429, 1000-0, 1096-1000, 2577-1096....and so on till end of file) and store the result into another txt file. I also need the subtracted answer to show the group that it belongs to.
By the way, the numbers to right of the comma is for grouping purposes

example:
172,28
1981,36
1250,37
1467,37
1231,38
34,38
57,39
1372,39
563,39
1000,41
96,41
1481,41

I would be nice if somebody could show me how to do this. I'm having a a major brain fart. The furthest I got is

Dim n1, n2 As Integer

        Dim lines() As String = IO.File.ReadAllLines("C:\Queried Master Total List.txt")
        For Each line As String In lines
            'do something with each single line


        Next

My thoughts of attack was:
       ''Create an array
       "Take two integers, n1 and n2
        ''open file for input
        ''read first integer into n1
        ''start of loop to read until end-of-file
        ''read integer into n2
        ''subtract n2 - n1 and save result in a second file
        ''move value of n2 into n1
        ''end of loop

I can think it, but I just cant code it. Please help.

Thank you very much.

 
    Sub ReadFileAndCompute()

        Dim StrConn As String

        Dim DA As New OleDbDataAdapter

        Dim DS As New DataSet

        Dim Str As String

        Dim ColumnCount As Integer

        Dim OuterCount As Integer

        Dim InnerCount As Integer

        Dim RowCount As Integer




        StrConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Results.xls;Extended Properties=Excel 8.0;"

        Dim objConn As New OleDbConnection(StrConn)

        If File.Exists("C:\Queried Master Total List.txt") Then
            File.Delete("C:\Queried Master Total List.txt")
        Else
           
        End If

        Try

            objConn.Open()

            If objConn.State = ConnectionState.Closed Then

                Console.Write("Connection cannot be opened")

            Else

                Console.Write("WelCome")

            End If

        Catch ex As Exception

            Console.Write(ex.ToString)

            Exit Sub

        End Try





        ' We need to read into this List.
        Dim list As New List(Of String)

        ' Open file.txt with the Using statement.
        Using r As StreamReader = New StreamReader("C:\Non-Duplicate Total List.txt")
            ' Store contents in this String.
            Dim line As String

            ' Read first line.
            line = r.ReadLine

            ' Loop over each line in file, While list is Not Nothing.
            Do While (Not line Is Nothing)
                

                Dim objCmd As New OleDbCommand("Select Row,Total from [Archive$]" & vbCrLf & _
                    "WHERE Total =" & line, objConn)

                objCmd.CommandType = CommandType.Text



                Dim ObjStreamWriter As StreamWriter

                'Added "True," to turn on Append Mode for StreamWriter

                ObjStreamWriter = New StreamWriter("C:\Queried Master Total List.txt")

                


                Dim Count As Integer

                Count = 0

                Try

                    DA.SelectCommand = objCmd

                    DA.Fill(DS, "XLData")

                Catch ex As Exception

                    Console.Write(ex.ToString)

                End Try



                RowCount = DS.Tables(0).Rows.Count

                ColumnCount = DS.Tables(0).Columns.Count



                For OuterCount = 0 To RowCount - 1

                    Str = ""

                    For InnerCount = 0 To ColumnCount - 1

                        Str &= DS.Tables(0).Rows(OuterCount).Item(InnerCount) & ","
                        'Str &= DS.Tables(0).Rows(OuterCount).Item(InnerCount)

                    Next
                    'Remove last character ,
                    Str = Str.Remove(Str.Length - 1)

                    ObjStreamWriter.WriteLine(Str)

                Next

                ObjStreamWriter.Close()

                Try

                Catch ex As Exception

                    MsgBox(ex.ToString)

                    Console.Write(ex.ToString)

                    Dim SW As New StreamWriter("C:\mylog.log")

                    SW.WriteLine(ex.ToString)

                    SW.Close()

                End Try

              
                ' Read in the next line.
                line = r.ReadLine

                objCmd.Dispose()

                objCmd = Nothing
            Loop
        End Using



   

        objConn.Close()

        objConn.Dispose()

        objConn = Nothing

        MsgBox("ReadFileAndCompute Created!")

    End Sub

Open in new window

0
Comment
Question by:NeallyNeal
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
4 Comments
 
LVL 20

Expert Comment

by:BuggyCoder
ID: 37824887
here you go, bit of linq and some stuff:-

var lines = File.ReadAllLines(string.Concat(Directory.GetCurrentDirectory(), @"\test.txt"));
            var lstData =
                lines
                    .Select(line => new
                                        {
                                            Value = Convert.ToInt32(line.Split(',')[0]),
                                            Id = Convert.ToInt32(line.Split(',')[1])
                                        })
                    .OrderBy(a => a.Id)
                    .ThenByDescending(a => a.Value);
                    

            int lastId = 0;
            int value = 0;

            var dicResults = new Dictionary<int, int>();

            foreach (var item in lstData)
            {
                if (lastId == 0) value = item.Value;

                if (lastId == item.Id)
                {
                    value = value - item.Value;
                }
                else
                {
                    if (lastId != 0)
                    {
                        dicResults.Add(lastId, value);
                        value = item.Value;
                    }
                }

                lastId = item.Id;
            }

            if(lastId!=0)
            {
                dicResults.Add(lastId, value);
            }

Open in new window

0
 

Author Comment

by:NeallyNeal
ID: 37824975
BuggyCoder,

I'm getting var is not defined. on line 18 of your code. I've converted the code to vb.net. what should I define var as?



Dim lines = File.ReadAllLines(String.Concat(Directory.GetCurrentDirectory(), "\test.txt"))
        Dim lstData = lines.[Select](Function(line) New With { _
         Key .Value = Convert.ToInt32(line.Split(","c)(0)), _
         Key .Id = Convert.ToInt32(line.Split(","c)(1)) _
        }).OrderBy(Function(a) a.Id).ThenByDescending(Function(a) a.Value)


        Dim lastId As Integer = 0
        Dim value As Integer = 0

        Dim dicResults = New Dictionary(Of Integer, Integer)()

        For Each item As var In lstData
            If lastId = 0 Then
                value = item.Value
            End If

            If lastId = item.Id Then
                value = value - item.Value
            Else
                If lastId <> 0 Then
                    dicResults.Add(lastId, value)
                    value = item.Value
                End If
            End If

            lastId = item.Id
        Next

        If lastId <> 0 Then
            dicResults.Add(lastId, value)
        End If
0
 
LVL 20

Accepted Solution

by:
BuggyCoder earned 2000 total points
ID: 37825049
here is working vb code for you, try this:-

Dim lines = File.ReadAllLines(String.Concat(Directory.GetCurrentDirectory(), "\test.txt"))
        Dim lstData = lines.[Select](Function(line) New With { _
         .Value = Convert.ToInt32(line.Split(","c)(0)), _
         .Id = Convert.ToInt32(line.Split(","c)(1)) _
        }).OrderBy(Function(a) a.Id).ThenByDescending(Function(a) a.Value)


        Dim lastId As Integer = 0
        Dim value As Integer = 0

        Dim dicResults = New Dictionary(Of Integer, Integer)()

        For Each item In lstData
            If lastId = 0 Then
                value = item.Value
            End If

            If lastId = item.Id Then
                value = value - item.Value
            Else
                If lastId <> 0 Then
                    dicResults.Add(lastId, value)
                    value = item.Value
                End If
            End If

            lastId = item.Id
        Next

        If lastId <> 0 Then
            dicResults.Add(lastId, value)
        End If

Open in new window

0
 

Author Closing Comment

by:NeallyNeal
ID: 37825193
BuggyCoder you need to change your name handle. You figured it out! There isn't any bugs in your logic. :-) Thank you for putting my mind to rest!

Thank you so much for your help!
0

Featured Post

Windows Server 2016: All you need to know

Learn about Hyper-V features that increase functionality and usability of Microsoft Windows Server 2016. Also, throughout this eBook, you’ll find some basic PowerShell examples that will help you leverage the scripts in your environments!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
Video by: ITPro.TV
In this episode Don builds upon the troubleshooting techniques by demonstrating how to properly monitor a vSphere deployment to detect problems before they occur. He begins the show using tools found within the vSphere suite as ends the show demonst…
Have you created a query with information for a calendar? ... and then, abra-cadabra, the calendar is done?! I am going to show you how to make that happen. Visualize your data!  ... really see it To use the code to create a calendar from a q…

722 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question