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/Microsoft/Development/.NET/Visual_Studio_.NET_2005/Q_23419970.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

.NET ProgrammingASP.NET

Avatar of undefined
Last Comment
fosiul01

8/22/2022 - Mon
naspinski

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

ASKER
fosiul01

I am using dot net 2.0
naspinski

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

All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
naspinski

Are you unable to upgrade?  3.0 makes a lot of useful updates and it's free. (3.5 is even better)
ASKER
fosiul01

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
naspinski

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

Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
naspinski

I just recommend the Generics route as it is much more efficient if you start getting larger ArrayLists
ASKER
fosiul01

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

ASKER
fosiul01

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

I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
ASKER CERTIFIED SOLUTION
Jorge Paulino

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
ASKER
fosiul01

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

Jorge Paulino


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!
ASKER
fosiul01

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!!!
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
ASKER
fosiul01

ok if i use this code :  _obj.Amount += TextBox4.Text it works

but still i dont understand, how its working
ASKER
fosiul01

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()
Jorge Paulino

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
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
ASKER
fosiul01

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.
Jorge Paulino

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!
ASKER
fosiul01

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
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
Jorge Paulino

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.
ASKER
fosiul01

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
Jorge Paulino

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!
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
ASKER
fosiul01

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.
Jorge Paulino

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)
ASKER
fosiul01

thats fine, i got it.
and thanks agian to stay with me.
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
Jorge Paulino

Glad I could help!
ASKER
fosiul01

HI jpaulino

can you please look at my this question
https://www.experts-exchange.com/Microsoft/Development/.NET/Visual_Studio_.NET_2005/Q_23440667.html

its Same of this one you answered