Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C#
public class MyObj
{
   public string MyObjName;
   
   public MyObj(string myObjName)
   {
      MyObjName = myObjName;
   }
}
 
public static Main(string[] args)
{
   List<MyObj> myObjs = new List<MyObj>();
   
   myObjs.Add(new MyObj("Obj1"));
   myObjs.Add(new MyObj("Obj2"));
   myObjs.Add(new MyObj("Obj3"));
   // etc...
}
 
If I wanted to find a specific MyObj e.g.(Obj100) in myObjs what is the fastest and most efficient way to go about this?
Posted 27-Dec-12 5:42am
Edited 27-Dec-12 5:43am
v3
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

Please also consider the simplest option, using System.Collections.Generic.List<T>.Find:
http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx[^].
 
In addition to a correct answer by Oleksandr Kulchytsky, please see my comments to this answer.
 
The thing about overriding of System.Object.Equals and System.Object.GetHashCode is not so trivial. I saw even pretty experienced developers who were confused. Short explanation is: it's important for some collection classes providing access by a key. For more detailed explanation, please see my past answer, recently updated:
Object.GetHashCode() Method in C#.Net[^].
 
This is interesting enough and very important to understand, please see.
 
Good luck,
—SA
  Permalink  
v3
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 4

    public class MyObj
    {
        public String MyObjName;
        public MyObj()
        {
 
        }
        public MyObj(String myObjName)
        {
            MyObjName = myObjName;
        }
        public void Hello()
        {
            Console.Write(MyObjName);
        }
    }
   
        static void Main()
        {
            List<myobj> myObjs = new List<myobj>();
            for (int i = 1; i < 101; i++)
            {
                myObjs.Add(new MyObj("Obj" + i));
            }
 

            object obj1 = Activator.CreateInstance(Type.GetType("Delegate.MyObj")) as String;
            MethodInfo mi = obj1.GetType().GetMethod("Hello");
            mi.Invoke(obj1, null);
 
        }
</myobj></myobj>
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

firs of all override method Equals and implement it logic in your class MyObj.
 
To find object in your's list you can laverage LINQ:
 
myObjs.FisrtOrDefault(x=>x.MyObjName.Equals("obj100",StringComparisson.OrdinalIgnoreCase))
  Permalink  
v3
Comments
Donald Allen at 27-Dec-12 11:54am
   
question: is this similar to myObjs.Find()? if so i'm wondering if this is a foreach or for-loop behind the sense. do you know?
Oleksandr Kulchytskyi at 27-Dec-12 11:58am
   
Yep , it similar to First(), expect one thing in case if there is no such element with specified criteria , method will return null.
And yep again, under the hood of LINQ located old-plain foreach , for =))
Donald Allen at 27-Dec-12 12:10pm
   
hey Oleksandr is there anyway I can avoid a linear search?
Oleksandr Kulchytskyi at 27-Dec-12 14:22pm
   
Hm , i think No.
Donald Allen at 27-Dec-12 12:13pm
   
i know i can use a HastTable or Dictionary but the reason why i can't is because my List which is actually a BindingList is bound to dataGridView and neither HashTable or Dictionary support data binding
Sergey Alexandrovich Kryukov at 27-Dec-12 22:07pm
   
Not bad, but it misses some important notes:
 
1) It's likely that the available implementation of System.Object.Equals is already good enough for the search;
2) It one overrides System.Object.Equals, System.Object.GetHashCode should also be overridden; a compiler will require that, for a good reason.
3) Also, System.Collections.Generic.List<T>.Find is good enough.
Don't you think so? (I voted 4.)
 
—SA
Oleksandr Kulchytskyi at 28-Dec-12 1:45am
   
Yep, completely agree with you, in that answer i had to pay more attention while have been mentioned about Equals method, but for some reason i have missed that,
And of course List.Find, also is quite good enough.
Thank for correction!
Sergey Alexandrovich Kryukov at 27-Dec-12 22:14pm
   
Actually, this thing with Equals and GetHashCode really needs some explanation. I added my own answer, mostly to complement yours and put all dots under 'i'. Please see.
—SA
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

  for each (object obj in myObjs){
         if (obj.gettype() == typeof(MyObj)){
             //... do your thing obj is MyObj
         }
  }
  Permalink  
Comments
Donald Allen at 27-Dec-12 11:52am
   
thx for the reply Adam, BUT what if I have 1000's of objects in my data structure. This won't be too efficient. I cant iterate over the entire collection it will be time consuming and resource intensive.
Adam R Harris at 27-Dec-12 11:55am
   
Depending on your framework version you could use LINQ like Oleksandr is suggesting.
Donald Allen at 27-Dec-12 12:02pm
   
ok, i'm not too familiar with linq i'll have to do a little reading...so does the solution that Oleksandr provided get around iterating over the entire collection? i want some kind of hash lookup without having to provide the object itself as the lookup item. would be cool if i could use a property of the object.
Adam R Harris at 27-Dec-12 12:04pm
   
No, LINQ will just handle the iterating for you. Essentially there is no way to pull all your objects of a specific type out of a collection without actually iterating through the entire collection.
Donald Allen at 27-Dec-12 12:09pm
   
so this won't be more efficient than the solution you provided (foreach)? is there anyway for me to get around O(N) Big O Notation?
Adam R Harris at 27-Dec-12 12:26pm
   
Not that i'm aware of, is there a reason you just don't keep your different types separate?
Either in a list of lists or a something similar?
Donald Allen at 27-Dec-12 12:30pm
   
i don't understand what suggesting can you give me an example?
Adam R Harris at 27-Dec-12 12:49pm
   
something like this:
public Dictionary<string, List<object>> myItems = new Dictionary<string, List<object>>();
 
public void AddItem(object item)
{
if (item is string)
{
if (!myItems.ContainsKey("strings"))
myItems.Add("strings", new List<object>());
 
myItems["strings"].Add(item);
}
else if (item is int)
{
if (!myItems.ContainsKey("integers"))
myItems.Add("integers", new List<object>());
 
myItems["integers"].Add(item);
}
else if ... you get the point
}
 
public object GetItem(string key)
{
if (myItems.ContainsKey(key))
return myItems[key];
else
return null;
}
 
Then you can just call GetItems("myObj") to get a list of all the myObj objects you added via the AddItem method
Donald Allen at 27-Dec-12 13:14pm
   
oh i get it! yeah, i had thought about something like that last night. I may have to accept the fact that i'm using the wrong collection for fast look up :(

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 OriginalGriff 315
1 Sergey Alexandrovich Kryukov 201
2 ChauhanAjay 156
3 PhilLenoir 154
4 ClimerChinna 140
0 Sergey Alexandrovich Kryukov 6,140
1 OriginalGriff 5,195
2 CPallini 2,473
3 Richard MacCutchan 1,607
4 Abhinav S 1,505


Advertise | Privacy | Mobile
Web02 | 2.8.140814.1 | Last Updated 28 Dec 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100