Link to home
Start Free TrialLog in
Avatar of fosiul01
fosiul01Flag for United Kingdom of Great Britain and Northern Ireland

asked on

Finding an Existing item in an array and Add them

Hi , this is an existing question : https://www.experts-exchange.com/questions/23419970/How-to-Find-An-existing-Record-in-an-array.html

If any one can use my existing code and advise me, how i will find an existing item in an array  .

if item is already in their then it will Add the amount with the existing item.
if its new item , it will add in the array thats all..



''''''''''''''''''''''''''''''
default.aspx( code behind)
''''''''''''''''''''''''''''''
Partial Class _Default
    Inherits System.Web.UI.Page
    Private al As ArrayList
 
 
    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim Obj As Add = New Add
        ' Bellow code is holing data is comming from textbox1.text
        Obj.Name = TextBox1.Text
        Obj.Id = TextBox2.Text
        Obj.Amount = TextBox4.Text
 
        '' Need to check if Same Id is already there or not. if yes, then it will Add the amount with the old ID
        Dim X As Integer  <<-----------------------------------
        For X = 0 To al.Count - 1
            if al("Id) = 
        Next
        'Inserting all Record in object in ArrayList.
        al.Add(Obj)
        Session("al") = al
    End Sub
 
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Session("al") IsNot Nothing Then
            al = CType(Session("al"), ArrayList)
        Else
            al = New ArrayList
        End If
 
    End Sub
 
    Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
        GridView1.DataSource = al
        GridView1.DataBind()
 
    End Sub
End Class
 
'''''''''''''''''
add.vb(class)
''''''''''''''''
Imports Microsoft.VisualBasic
 
Public Class Add
    Private _StrName As String
    Private _IntId As Integer
    Private _IntAmount As Integer
 
 
    Public Property Name() As String
        Get
            Return _StrName
        End Get
        Set(ByVal Value As String)
            _StrName = Value
        End Set
    End Property
    Public Property Id() As Integer
        Get
            Return _IntId
        End Get
        Set(ByVal value As Integer)
            _IntId = value
        End Set
    End Property
 
    Public Property Amount() As Integer
        Get
            Return _IntAmount
        End Get
        Set(ByVal value As Integer)
            _IntAmount = value
        End Set
    End Property
End Class

Open in new window

Avatar of naspinski
naspinski
Flag of United States of America image

This is very easy _if_ you are using .net 3.0 or higher and Generics, here is an example
Imports System.Collections.Generic
 
Partial Class vb_arrays
    Inherits System.Web.UI.Page
 
 
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'make dummy list for demonstration'
        Dim al As ArrayList = New ArrayList()
        al.Add(2)
        al.Add(5)
        al.Add(6)
        'use these numbers to try to add them'
        Dim addThese() As Integer = {1, 2, 3, 4, 5, 6, 7}
        For Each i In addThese
            'run the sub to try to insert them if they are new'
            InsertIfNotExistsInList(al, i)
        Next
 
        'print out what is in the list now to see results'
        Response.Write("<br />Items in list<br />")
        For Each item In al
            Response.Write(item & "<br />")
        Next
 
    End Sub
 
    Sub InsertIfNotExistsInList(ByVal list As ArrayList, ByVal i As Integer)
        If Not list.Contains(i) Then
            list.Add(i)
            Response.Write(i & " was not in the list, it was added<br />")
        Else
            Response.Write(i & " was already in the list<br />")
        End If
    End Sub
 
End Class

Open in new window

Avatar of fosiul01

ASKER

I am using dot net 2.0
Really all the code you need to use is here, the rest I provided was for demonstration. I used Integers, but you have objects (Add it looks like?), you would just have to change that.
    Sub InsertIfNotExistsInList(ByVal list As ArrayList, ByVal i As Add)
        If Not list.Contains(i) Then
            list.Add(i)
            Response.Write(i & " was not in the list, it was added<br />")
        Else
            Response.Write(i & " was already in the list<br />")
        End If
    End Sub

Open in new window

Are you unable to upgrade?  3.0 makes a lot of useful updates and it's free. (3.5 is even better)
Problem is my Web hosting company does not upgrade their asp.net from 2.0 to 3>

give me 5 min, i will try as you said, see what result i got, then will come back to you within 10 min
ok, here is a 2.0 solution if you can't (change to objects from integers)
    Sub InsertIfNotExistsInList(ByVal list As ArrayList, ByVal x As Integer)
        Dim alreadyHere As Boolean = False
        For i = 0 To list.Count - 1
            If list(i) = x Then
                alreadyHere = True
            End If
        Next
 
        If Not alreadyHere Then
            list.Add(x)
            Response.Write(x & " was not in the list, it was added<br />")
        Else
            Response.Write(x & " was already in the list<br />")
        End If
    End Sub

Open in new window

I just recommend the Generics route as it is much more efficient if you start getting larger ArrayLists
ommm problem is, you are inserting data in Array by STatically
but I am trying to insert data dynamically with bellow code

and also , main Point is : if it see Same Item is inserting again, it will update the amount .

Example : shoping cart- if you try to enter same item, it just Add with the existing one , is not it ??

Else
  it will Add the item in the array.
thats all



Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
 
' From here ----- its inserting Record in the object       
 Dim Obj As Add = New Add
        ' Bellow code is holing data is comming from textbox1.text
        Obj.Name = TextBox1.Text
        Obj.Id = TextBox2.Text
        Obj.Amount = TextBox4.Text
' till here---------------------
' Now i will have to check in al( Array list)
 
        al.Add(Obj)
        Session("al") = al
    End Sub

Open in new window

HI yah,
i am having problme to understand the code you provided

can you please show me how to complete my task by using my code  ??

I would be realy greatefull if you can give me a workable code by using my code.
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
 
' From here ----- its inserting Record in the object       
 Dim Obj As Add = New Add
        ' Bellow code is holing data is comming from textbox1.text
        Obj.Name = TextBox1.Text
        Obj.Id = TextBox2.Text
        Obj.Amount = TextBox4.Text
' till here---------------------
' Now i will have to check in al( Array list)
 
        al.Add(Obj)
        Session("al") = al
    End Sub

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Jorge Paulino
Jorge Paulino
Flag of Portugal image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
HI thanks
its works
but i want to know Something :

1. You have created another object is not it ?? which is _obj  
       If _obj.Id = Obj.Id Then

2. if i add this code to your existing code :   _obj.Amount += 1

Result will be : if i type Same Id 2 time, it will Add the amount with the previous one. which is fine

but one thing i dont understand, how the new value of amount is overridding the old value ?? where you did  that ??

 i am asking because : if the Code see new ID it will add the item in the array. but if it see the id is already there, it wil just give a message, but _obj.Amount += 1  actually overriding the old amount,

 

 Dim Obj As Add = New Add
 
        ' Bellow code is holing data is comming from textbox1.text
        Obj.Name = TextBox1.Text
        Obj.Id = TextBox2.Text
        Obj.Amount = TextBox4.Text
 
 
        ' If there is data in the arraylist
        If al.Count > 0 Then
            Dim idExists As Boolean = False
 
            ' Loop in the array items
            For x As Integer = 0 To al.Count - 1
 
                ' Convert each item to type Add
                Dim _obj As Add = CType(al(x), Add)
 
                ' compare if the ID already exists
                If _obj.Id = Obj.Id Then
                    idExists = True
                    ' Updating the Amount for Existing Item
                    _obj.Amount += 1   '-------------------------- Adding amount for dupplicate item----
                    Exit For
                End If
 
            Next
 
            ' If the ID doesn't exists add the new Obj 
            If Not idExists Then
                al.Add(Obj)
            Else
                MsgBox("ID already exists in the array")
            End If
 
        Else
            al.Add(Obj)
            Session("al") = al
        End If

Open in new window


1. No I have converted using ctype an existing object in the arraylist to type "Add"

2. Why do you use this _obj.Amount += 1 ? I don't understand this problem!
ok look at this example :  ( Example of a Shoping Cart)

Start  of the programm
 User inserted  :ItemName :Books, ID : 1 , Amount : 500   -> its a new   item so the Code will Insert this items in the Array

AGain if user  insert Same ID : ITemName: Books , ID:1, Amount:500  -> so the code will see, user has inserted Same ID again so it wil Add 500 again with the previous 500 .
so in array it will be like this

              ITemName  id   Amount
Record : Books          1      1000  -> here Same ID added 2 times ( amount)
              Computer     2        700   -> Different ID
              Laptop         3        500 -> Different ID

HOpe this make sence ??

Oppsss there is a problem :    _obj.Amount += 1

here Amount is increasing by 1!!!!

but i want to add amount with the prevous amount!!!
ok if i use this code :  _obj.Amount += TextBox4.Text it works

but still i dont understand, how its working
Ok i Understand , how this code working except one thing :
please explain me this

You said, you are Converting Each item to type  ADd by following code:
Dim _obj As Add = CType(al(x), Add)

NOw i have Added this Code which is under _obj by following code :

_obj.Amount += TextBox4.Text

Now my question is , how its effecting the Array al ?? Because i am modifying Amount in _obj.amount, but its actually Adding in main array list  (al)

Because, if I bind al to Grid view, i can see the amount has been change with this code :
 GridView1.DataSource = al
        GridView1.DataBind()
Ok, you want to update the information to an existing object in the arraylist.

Just remove the existing one and add it again with the changes

You can use al.Remove() method
I dont want to remove from Array list.

Your code works fine. but i just want explanation of my previous question, how this code is orverriding al from _obj.
When you do this:

Dim _obj As Add = CType(al(x), Add)

you are using the object that are in the arraylist. It's a normal usage and a convertion from a gerenic type to your type "Add"

I don't understand what you need more!
Hi, i am sorry, because, i am unable to make it clear actually where is my problem .

i have attached a picture, i am trying my best to explain you what actually i want to understand.

Here, what i am seeing is: you are copying record in _obj which is comming of obj

but i am not seeing , how record is going from _obj to obj

may be i am thinking too hard to understand an easy concept

Problem.GIF
After I look the picture I still get the same impression!

You want to add to the previous amount the actual (if you find). Ex:

You have:

ID:1
Name:myName
Amount:10

Then you try to add a new one with the same Id. You want to have this as result:

Id:1
Name:myName
Amount:20

If this is the case you must remove the current object and add it again with the new changes.

Tell me if it's this and I will help you with the code.
as i said, this code fine, i dont have any problem of this code, its working.

But you got me wrong. you are saying, i will have to Remove Current object and add it again.

Which i dont want.

after typing the 2nd record ( amount 20)

then out put would be : Id 1
                                       name : myname
                                       Amount: 30   -> 10 from First Entry and 20 from 2nd Entry

which is fine, this code is showing 30.

but my question is how the existing Record  of Original Array is overriding by _obj

i have attached 2 pictures
firstEntry
and
2nd Entry

if it does not help then i will accept your code anyway.
 




FirstEntry.GIF
2ndEntry.GIF
Ok, now I understand!!!

When you using the _obj you are working with the information (object) on the arraylist. If you change something you are also changing the information on the array. Try to change the name after the amount ... ex:

_obj.Amount += obj.Amount
_obj.Name = "Test"

This will change that information on that Item also.

hope this information helps you understand it!
Here you go!!!
Now you gave me proper answer!!

but i am new with this concept
When you using the _obj you are working with the information (object) on the arraylist. If you change something you are also changing the information on the array.

is this because of your this comments: Dim _obj As Add = CType(al(x), Add) or its just the beaviour of arraylist ??

No more question after that.
You are using the item in the arralist into the variable _obj. You converte it to type Add to have the intelissense and all the methods and properties that he has.

Is a normal method and as nothing to do with the arraylist.

I'm also sorry to not explain right but english is not my motherlanguage and I do better then I explain it (at least in english)
thats fine, i got it.
and thanks agian to stay with me.
Glad I could help!
HI jpaulino

can you please look at my this question
https://www.experts-exchange.com/questions/23440667/Datalist-and-Arraylist.html

its Same of this one you answered