Reputation: 63
How is it possible to find a specific object from a list? Lets say i have a function that takes an object and a list that contains objects of this type and returns the number at which position the specific object is found.
The only way i could think of a solution is to run the list through with a foreach loop, but isn't there a better way?
Thanks
Upvotes: 0
Views: 1789
Reputation: 101
You can use the IndexOf(T item)
method:
myList.IndexOf(myItem);
It returns the index of the first occurrence of the item.
Upvotes: 1
Reputation: 13059
To see whether object is there You might just need List<T>.Contains
method
It states,
Determines whether an element is in the List.
And you need to use it like List<T>.Contains(T type item)
, where T
is the same type of List
and item
you need to compare. In your case it's a the type of Object
And to return the index you can use List<T>.IndexOf
Method
Searches for the specified object and returns the zero-based index of the first occurrence within the entire List.
Simple Console program
class Program
{
static void Main(string[] args)
{
MyType a = new MyType() { id = 10 };
MyType b = new MyType() { id = 20 };
MyType c = new MyType() { id = 30 };
List<MyType> testList = new List<MyType>();
testList.Add(a);
testList.Add(b);
Console.WriteLine(testList.Contains(a)); // <= Will return true
Console.WriteLine(testList.Contains(c)); // <= Will return false
Console.WriteLine(testList.IndexOf(a)); // <= will return 0 : the index of object a
Console.ReadKey();
}
}
// A simple class
class MyType
{
private int ID;
public int id
{
get { return ID; }
set { ID = value; }
}
}
Upvotes: 0
Reputation: 310980
You can use method IndexOf
or if you use a special condition then you can use method
public int FindIndex(Predicate<T> match);
where match is delegate
public delegate bool Predicate<T>(T obj);
In fact it is similar to standard C++ algorithm std::find_if
Upvotes: 0
Reputation: 5135
You could use linq expressions
List.where(condition)
Or
List.Select(condition).FirstOrDefault
Based on search condition it will return the item you want.
Upvotes: 0
Reputation: 726579
The only way i could think of a solution is to run the list through with a
foreach
loop
Generally, you need a loop (a for
or foreach
) to find an object in a list. You could use it directly, or through a function that iterates over list elements, but there is going to be a loop. There is no way around it: unless you know something special about the way the elements of the array are arranged, you have to look at them all.
One case of knowing something special about arrangement of elements is knowing that an array is sorted. If this is the case, and when you know the value of the attribute on which the element is sorted, you can find the element much faster by using binary search.
Upvotes: 0