Re: iterating over collection

Fabian Schmied <[email protected]>
Newsgroups gmane.comp.windows.devel.dotnet.cx
Message-ID <[email protected]>
[...]

> Is there a way (I can't figure one out and don't know if it's possible since
> the collection classes are all of specific object types) to somehow have one
> method into which I could pass any of the collection classes (since the are
> all based on the Dictionary<> object though with different generic objects
> even though all based on the abstract base object) and then somehow loop
> over them after casting to the base object type?

Since I don't know your exact code/classes/requirements [1], I'm not
sure, but I think the Dictionary<object, BaseObject> approach Adrian
suggested might not work for you, since a Dictionary<object, Derived>
is not assignable to a Dictionary<object, BaseObject variable or
parameter.

Because you are using generic types, it would make sense to use a
generic method as well:

T FindObject<T>(string mn, Dictionary<..., T> c) where T : BaseObject {
  foreach (T bo in c.Values {
    if (bo.MagicNamber == mn) {
      return bo;
    }
  }
  return null;
}

Alternatively, you could also use a collection library such as
Wintellect PowerCollections, which has a predefined FindFirstWhere
method, which could be used like this:

Dictionary<..., Derived> collection;
Derived d = FindFirstWhere(collection.Values, delegate(Derived element) {
  return element.MagicNumber == mn;
});

FindFirstWhere has the advantage that it can be used for any
enumerable object, not only for your dictionaries. It is probably
defined similar to the following:

T FindFirstWhere<T>(IEnumerable<T> collection, Predicate<T> criterion) {
  foreach (T element in collection) {
    if (criterion(element)) {
      return element;
    }
  }
  return default(T);
}

Regards,
Fabian

===================================
This list is hosted by DevelopMentor®  http://www.develop.com

View archives and manage your subscription(s) at http://discuss.develop.com
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.