tags:

views:

63

answers:

3

I have a Queue that contains a collection of objects, one of these objects is a class called GlobalMarker that has a member called GlobalIndex.

What I want to be able to do is find the index of the queue where the GlobalIndex contains a given value (this will always be unique).

Simply using the Contains method shown below returns a bool. How can I obtain the queue index of this match?

RealTimeBuffer
  .OfType<GlobalMarker>()
  .Select(o => o.GlobalIndex)
  .Contains(INT_VALUE);
+9  A: 

If you need the index then perhaps you are using the wrong collection type. A queue is not designed to support random access (like an array or a List<T>). If you need random access then perhaps you should be using a type that implements IList<T>.

Andrew Hare
+1 for this is exactly what I would have said.
Greg D
+1  A: 

Queue's don't provide an interface that returns the index of a matching element, neither, unfortunately does LINQ.

You may want to consider using a List<> or Array if you need such methods. However, it is possible to treat the Queue as an IEnumerable and roll your own implementation - alternatively you could create a List from the queue and use IndexOf:

RealTimeBuffer.OfType<GlobalMarker>()
              .Select(o => o.GlobalIndex).ToList().IndexOf( INT_VALUE );
LBushkin
A: 

If all Items in your collection are of type GlobalMarker, it is better to use ILis<>

 List<GlobalMarker> RealTimeBuffer = new List<GlobalMarker>();
 GlobalMarker globalMarker = 
        RealTimeBuffer.SingleOrDefault(o => o.GlobalIndex == 1);

If they are not All the same Type, You may use IList, but keep in mind, It is not a recommended approach. Here is a sample which will return GlobalMarker object

   ArrayList RealTimeBuffer = new ArrayList();
   RealTimeBuffer.Add(new GlobalMarker(){ GlobalIndex = 3 });
   GlobalMarker globalMarker = 
   RealTimeBuffer.OfType<GlobalMarker>().FirstOrDefault(o => o.GlobalIndex == INT_VALUE);
Asad Butt