简体   繁体   中英

Distinct Types from a generic Collection

I have a list of objects

List<Animals> animals

I'm trying to access every distinct Type of animal inside animals (eg Dog , Cat , Walrus ) and get it into another generic collection using this kind of idea:

List<Type> types 
    = animals.SelectMany<Animal, Type>(a => a.GetType()).Distinct<Type>();

or

// EqualityComparer<T> is a generic implementation of IEqualityComparer<T>
List<Type> types 
    = animals.Distinct<Animal>(new EqualityComparer<Animal>((a, b) => a.GetType() == b.GetType())); 

But I'm having trouble getting either of these to compile.

Why SelectMany ? Standard Select should do the job:

List<Type> types = animals.Select(x => x.GetType()).Distinct();

How about a Dictionary<Type, List<Animal>> where any list within the list only contains elements of the key type?

var typeSpecficGroups = animals.GroupBy(animal => animal.GetType());
var dictOfTypes = typeSpecficGroups.ToDictionary(group => group.Key, group => group.ToList());

Now you can ask the dictionary if it has a specific animal and get the corresponding list of animals back. The drawback is that you have to cast each element within the list to the concrete type:

List<Animal> matchingList;

if (dictOfTypes.TryGetValue(typeof(Dog), out matchingList))
{
    var dogs = matchingList.Cast<Dog>();

    foreach (var dog in dogs)
    {
        dog.FindBone();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM