tags:

views:

145

answers:

2

How can I rewrite or is there a way to writing my own custom function that simulates the Custom System.Collections.Generic.Contains but only factors in certain Public Properties of a Custom Object?

For example if I have a custom Object with Properties Name and ID, I would like my Unique Value List to contain all the DISTINCT Names. The ID in this case is irrelevant.

List allvalues = new List ({0, "Burger"}, {1, "Pizza"}, {2, "burger"})

I would like it to return me a List which contains the first Object of 0, Burger and 1, Pizza... Irrespective of the ID and the Case of the Name.

Thanks.

A: 

Yes use yield return as in:

   private Collection<T> internalCollection;

    public Collection<T> GetDistinctList<T>()
    {
        List<string> names = new List<string>();
        foreach(T thisT in internalCollection)
           if (!names.Contains(thisT.Name)
           {
               names.Add(thisT.Name);
               yield return thisT;
           }
    }
Charles Bretana
A: 

I'm very unclear how the Contains(...) related to the List ({0, "Burger"}, {1, "Pizza"}, {2, "burger"}) stuff. Can you clarify? In general, you might want to look at providing a custom Equals()/GetHashCode(), or IEquatable<T>, or an IEqualityComparer<T>. Alternatively, LINQ has lots of ways to make this simple - do you have access to LINQ?

Marc Gravell