Reputation: 4125
Is there an easy way (maybe a method) of retrieving an object from a list depending on if one of its property matches the requested one?
For example, if I have List<Animal>
and the Animal
class has a property Size
. How could I get the objects from a list with Size=42
? It's like filtering but isn't there an easier and faster way of doing it? Insted of using ICollectionView
.
public Animal getAnimalWithSize42 (List<Animal> animList)
{
List<Animal> size42Animals = new List<Animal>
foreach (Animal anim in animList)
{
if(anim.Size==42)
size42Animals.Add(anim);
}
return size42Animals;
}
Is this some kind of implemented function?
Upvotes: 1
Views: 67
Reputation: 14565
You can use LINQ, that's generally the easiest way. Something like this maybe:
IEnumerable<Animal> getAnimalWithSize42(IEnumerable<Animal> animList)
{
return animList.Where(animal => animal.Size == 42);
}
If you wanted to be slick - you could even let the caller pass in what they want to retrieve:
IEnumerable<Animal> getAnimalsMeetingCriteria(IEnumerable<Animal> animals, Func<Animal, bool> filter)
{
return animals.Where(filter);
}
Make sure you add a reference to System.Linq
in the file that needs to use this.
Upvotes: 5
Reputation: 1954
LINQ is ideal for this purpose:
public Animal getAnimalWithSize42 (List<Animal> animList)
{
return animList.Where(a => a.Size == 42);
}
Upvotes: 1
Reputation: 9201
Use LINQ to do it.
List<Animal> size42Animals = animList.Where(anim => anim.Size == 42).ToList();
Upvotes: 1
Reputation: 57222
You can use LINQ:
return animList.Where(anim => anim.Size == 42);
Upvotes: 4