Finding a particular field from ArrayList of struct

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • bbg9507
    New Member
    • Jul 2007
    • 3

    Finding a particular field from ArrayList of struct

    Hi, question about using ArrayList from C# newbie,

    I managed to make my array list which holds a number of structs:

    struct myStruct
    {
    public int field1;
    public int field2;
    }

    static ArrayList myArray = new ArrayList();

    How could I find a struct that holds a particular value in field1?
    IndexOf()?

    Bob
  • bbg9507
    New Member
    • Jul 2007
    • 3

    #2
    I wrote a method like:

    Code:
    int findStruct(ArrayList arr)
    {
      int idx = -1;
      for (int i = 0; i < arr.Count; i++)
        if (((myStruct)arr[i]).id == 0x0302)
          {
          idx = i;
          break;
          }
    
           return idx;
    }
    Any other fancy way to do a job?

    Bob



    Originally posted by bbg9507
    Hi, question about using ArrayList from C# newbie,

    I managed to make my array list which holds a number of structs:

    struct myStruct
    {
    public int field1;
    public int field2;
    }

    static ArrayList myArray = new ArrayList();

    How could I find a struct that holds a particular value in field1?
    IndexOf()?

    Bob

    Comment

    • RoninZA
      New Member
      • Jul 2007
      • 78

      #3
      You could use the IndexOf() method of the ArrayList:
      Code:
      myStruct struct = new MyStruct();
      struct.Field1 = 1; //or whatever int you're searching for
      struct.Field2 = 2; //ditto
      
      int foundIndex = myArrayList.IndexOf(struct);

      Comment

      • bbg9507
        New Member
        • Jul 2007
        • 3

        #4
        Originally posted by RoninZA
        You could use the IndexOf() method of the ArrayList:
        Code:
        myStruct struct = new MyStruct();
        struct.Field1 = 1; //or whatever int you're searching for
        struct.Field2 = 2; //ditto
        
        int foundIndex = myArrayList.IndexOf(struct);
        Thanks for reply RoninZA,

        I guess IndexOf() can be used as you suggested when I know all field values.
        What if I know just one of the field and don't care other fields?

        Bob

        Comment

        • RoninZA
          New Member
          • Jul 2007
          • 78

          #5
          Best way would be to loop through the structure and try and find the index you are looking for.

          Comment

          Working...