tags:

views:

101

answers:

4

Given a collection with an object in it - I need a way to find out if this object is also member of some other collection.

I.E in some sort of pseudo code

object o;

Collection<object> col1;
col1.Add(o);

Collection<object> col2;
col2.Add(o);

MagicWords.GetTheReferingCollectionsTo(o);

Where GetTheReferingCollectionsTo should return col1 and col2.

Do anyone know of a way to accomplish someting like that in C#

+3  A: 

AFAIK you can't do that programmatically unless implementing your own collection with tracking references.

aloneguid
I believe this is the principle of Encapsulation.
MunkiPhD
A: 

There is a similar post you should check that out.

affan
+1  A: 

If you think your app needs that, it's time to look at whether the design is sound. It likely is not.

I'm sure you could achieve what you want by making clever use of several Dictionary<TKey,TValue> 'collections' and check for your object's key value by calling ContainsKey() on the dictionary object.

Wim Hollebrandse
A: 

If you know what collections to search when you call your querying method you could do something similar to this

   class Program {
      static void Main(string[] args)
      {
         List<int> ints = new List<int>();
         List<int> ints2 = new List<int>();
         List<int> ints3 = new List<int>();
         for (int i = 0; i < 5; ++i) ints.Add(i);
         for (int j = 0; j < 5; ++j) ints2.Add(j);
         for (int k = 0; k < 3; ++k) ints2.Add(k);

          List<ICollection<int>> rets = GetRefs<int>(3, ints, ints2, ints3);

          Console.WriteLine(string.Format("{0} out of {1} collections contain a reference to {2}", rets.Count, rets.Capacity, 3));

          Console.ReadKey();
      }

      public static List<ICollection<T>> GetRefs<T>(T o, params ICollection<T>[] collections)
      {
         List<ICollection<T>> ret = new List<ICollection<T>>(collections.Length);
         foreach (ICollection<T> obj in collections)
         {
            if (obj.Contains(o)) ret.Add(obj);
         }
         return ret;
      }}

output is: 2 out of 3 collections contain a reference to 3

Jamie Altizer
That's just the problem. I don't know which collections to search in.
Jan Ohlson