C#學習Predicate
using System;
using System.Reflection;
using System.Collections.Generic;
using System.Drawing;
namespace Predicate
{
/// <summary>
/// Represents the method that defines a set of criteria and determines whether the specified object meets
/// those criteria
/// </summary>
class Program
{
static void Main(string[] args)
{
// The following example uses a Predicate<T> delegate with the Array.Find method to search an array of
// Pointer structures.The example explicitly defines a Predicate<T> delagate named predicate and assigns
// it a method named FindPoints that return true if the product of Point.X and Point.Y fields is greater than
// 100,000.Note that is it necessary to use a lambda expression rather than to explicitly define a delegate
// of type Predicate<T> as the second example illustrate.
// Create an array of Point structures
Point[] points =
{
new Point(100,200),
new Point(150,250),
new Point(250,375),
new Point(275,390),
new Point(296,400)
};
// Define the Predicate<T> delegate.
Predicate<Point> predicate = FindPoints;
// Find the first Point structure for whitch x times y is greater than 100000
Point first = Array.Find(points, predicate);
// Display the first structure found.
Console.WriteLine($"Found:X={first.X},Y={first.Y}");
Console.ReadKey();
}
private static bool FindPoints(Point ptn)
{
return ptn.X * ptn.Y > 100000;
}
}
}
The following example is identical to the previous example, except that it uses a lambda expression to represent the Predicate delegate
// Create an array of Point structures
Point[] points =
{
new Point(100,200),
new Point(150,250),
new Point(250,375),
new Point(275,390),
new Point(296,400)
};
// Define the Predicate<T> delegate.
Predicate<Point> predicate = FindPoints;
// Find the first Point structure for whitch x times y is greater than 100000
Point first = Array.Find(points, x => x.X * x.Y > 100000 );
// Display the first structure found.
Console.WriteLine($"Found:X={first.X},Y={first.Y}");
Console.ReadKey();
}
Array.FindAll的用法
using System;
using System.Reflection;
using System.Collections.Generic;
namespace Predicate_過濾
{
class Program
{
static void Main(string[] args)
{
List<Student> studens = new List<Student>
{
new Student("asd",18,100),
new Student("qwe",20,60),
new Student("dfg",30,70),
new Student("vbn",56,89)
};
foreach(var stu in studens.FindAll(x=>x.Age>20).FindAll(y=>y.Score>80))
{
Console.WriteLine($"Name:{stu.Name} \t Age:{stu.Age} \t Score:{stu.Score}");
}
Console.ReadKey();
}
}
class Student
{
public Student(string name,int age,int score)
{
this.Name = name;
this.Age = age;
this.Score = score;
}
public int Score { get; set; }
public int Age { get; set; }
public string Name { get; set; }
}
}