Home > Net >  Use FindAll() method on List<T>
Use FindAll() method on List<T>

Time:11-03

I have a list of objects with two properties each. I'd like to sort some of them out into another list based on one of their properties by using FindAll(). See example code below:

namespace Example {

    class Tower {
         public string name { get; set; }
         public int hight { get; set; }
    }

    class Program {
          static void Main (string[] args) {
                 List<Tower> towers = new List<Tower>();

                 towers.Add(new Tower() { Name = "tower1", Hight = 25 });
                 towers.Add(new Tower() { Name = "tower2", Hight = 50 });
                 towers.Add(new Tower() { Name = "tower3", Hight = 25 });

                 List<Tower> short_towers = towers.FindAll(new Tower() { Hight = 25 });
          }
     }
}

But it always says:

failed converting Example.Tower into System.Predicate<Example.Tower>'.

What am I doing wrong? Does someone have any advice?

CodePudding user response:

List<T>.FindAll requires a delegate as its parameter, not an instance of T. For example:

List<Tower> short_towers = towers.FindAll(t => t.Hight == 25);

Though perhaps, given the name of the variable, you want all towers 25 or under:

List<Tower> short_towers = towers.FindAll(t => t.Hight <= 25);

CodePudding user response:

List<T>.FindAll takes a delegate as input, in particular a Predicate<T>.

The Predicate<T> delegate can be defined as follows:

private bool FindShortTowers(Tower t)
{
    return t.Height <= 25;
}

// then, in some other method:

Predicate<Tower> predicate = FindShortTowers;
var shortTowers = towers.FindAll(predicate);

It is however customary to use a lambda expression rather than to explicitly define a delegate of type Predicate<T>:

var shortTowers = towers.FindAll(t => t.Height <= 25);

You can also use Enumerable.Where from System.Linq:

var shortTowers = towers.Where(t => t.Height <= 25);
  • Related