Solved

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

Posted on 2012-04-09
4
740 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
  • 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 500 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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.

706 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

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now