C#中的谓词委托

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/556425/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 08:04:08  来源:igfitidea点击:

Predicate Delegates in C#

c#.netpredicate

提问by Canavar

Can you explain to me:

你能给我解释一下吗:

  • What is a Predicate Delegate?
  • Where should we use predicates?
  • Any best practices when using predicates?
  • 什么是谓词委托?
  • 我们应该在哪里使用谓词?
  • 使用谓词时有什么最佳实践吗?

Descriptive source code will be appreciated.

描述性源代码将不胜感激。

采纳答案by Andrew Hare

A predicate is a function that returns trueor false. A predicate delegate is a reference to a predicate.

谓词是一个返回trueor的函数false。谓词委托是对谓词的引用。

So basically a predicate delegate is a reference to a function that returns trueor false. Predicates are very useful for filtering a list of values - here is an example.

所以基本上谓词委托是对返回trueor的函数的引用false。谓词对于过滤值列表非常有用 - 这是一个示例。

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<int> list = new List<int> { 1, 2, 3 };

        Predicate<int> predicate = new Predicate<int>(greaterThanTwo);

        List<int> newList = list.FindAll(predicate);
    }

    static bool greaterThanTwo(int arg)
    {
        return arg > 2;
    }
}

Now if you are using C# 3 you can use a lambda to represent the predicate in a cleaner fashion:

现在,如果您使用 C# 3,您可以使用 lambda 以更简洁的方式表示谓词:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<int> list = new List<int> { 1, 2, 3 };

        List<int> newList = list.FindAll(i => i > 2);
    }
}

回答by Adam Carr

Just a delegate that returns a boolean. It is used a lot in filtering lists but can be used wherever you'd like.

只是一个返回布尔值的委托。它在过滤列表中被大量使用,但可以在您想要的任何地方使用。

List<DateRangeClass>  myList = new List<DateRangeClass<GetSomeDateRangeArrayToPopulate);
myList.FindAll(x => (x.StartTime <= minDateToReturn && x.EndTime >= maxDateToReturn):

回答by LukeH

There's a good article on predicates here, although it's from the .NET2 era, so there's no mention of lambda expressions in there.

有一个关于谓词的好文章在这里,虽然它从.NET2时代的,所以有lambda表达式没有提及在那里。

回答by WestDiscGolf

Leading on from Andrew's answer with regards to c#2 and c#3 ... you can also do them inline for a one off search function (see below).

从 Andrew 对 c#2 和 c#3 的回答开始……您也可以将它们内联用于一次性搜索功能(见下文)。

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<int> list = new List<int> { 1, 2, 3 };

        List<int> newList = list.FindAll(delegate(int arg)
                           {
                               return arg> 2;
                           });
    }
}

Hope this helps.

希望这可以帮助。

回答by danlash

If you're in VB 9 (VS2008), a predicate can be a complex function:

如果您使用的是 VB 9 (VS2008),谓词可以是一个复杂的函数:

Dim list As New List(Of Integer)(New Integer() {1, 2, 3})
Dim newList = list.FindAll(AddressOf GreaterThanTwo)
...
Function GreaterThanTwo(ByVal item As Integer) As Boolean
    'do some work'
    Return item > 2
End Function

Or you can write your predicate as a lambda, as long as it's only one expression:

或者,您可以将谓词编写为 lambda,只要它只有一个表达式:

Dim list As New List(Of Integer)(New Integer() {1, 2, 3})
Dim newList = list.FindAll(Function(item) item > 2)

回答by lukaszk

The predicate-based searching methods allow a method delegate or lambda expression to decide whether a given element is a “match.” A predicate is simply a delegate accepting an object and returning true or false: public delegate bool Predicate (T object);

基于谓词的搜索方法允许方法委托或 lambda 表达式决定给定元素是否是“匹配”。谓词只是一个接受对象并返回 true 或 false 的委托: public delegate bool Predicate (T object);

   static void Main()
        {
            string[] names = { "Lukasz", "Darek", "Milosz" };
            string match1 = Array.Find(names, delegate(string name) { return name.Contains("L"); });
            //or
            string match2 = Array.Find(names, delegate(string name) { return name.Contains("L"); });
            //or
            string match3 = Array.Find(names, x => x.Contains("L"));


            Console.WriteLine(match1 + " " + match2 + " " + match3);     // Lukasz Lukasz Lukasz
        }
        static bool ContainsL(string name) { return name.Contains("L"); }

回答by Gul Md Ershad

What is Predicate Delegate?

什么是谓词委托?

1) Predicate is a feature that returns true or false.This concept has come in .net 2.0 framework. 2) It is being used with lambda expression (=>). It takes generic type as an argument. 3) It allows a predicate function to be defined and passed as a parameter to another function. 4) It is a special case of a Func, in that it takes only a single parameter and always returns a bool.

1) Predicate 是一个返回true 或false 的特性。这个概念在.net 2.0 框架中已经出现。2) 它与 lambda 表达式 (=>) 一起使用。它接受泛型类型作为参数。3) 它允许定义一个谓词函数并将其作为参数传递给另一个函数。4) 这是 a 的一个特例Func,因为它只接受一个参数并且总是返回一个布尔值。

In C# namespace:

在 C# 命名空间中:

namespace System
{   
    public delegate bool Predicate<in T>(T obj);
}

It is defined in the System namespace.

它在 System 命名空间中定义。

Where should we use Predicate Delegate?

我们应该在哪里使用谓词委托?

We should use Predicate Delegate in the following cases:

我们应该在以下情况下使用 Predicate Delegate:

1) For searching items in a generic collection. e.g.

1) 用于搜索通用集合中的项目。例如

var employeeDetails = employees.Where(o=>o.employeeId == 1237).FirstOrDefault();

2) Basic example that shortens the code and returns true or false:

2) 缩短代码并返回 true 或 false 的基本示例:

Predicate<int> isValueOne = x => x == 1;

now, Call above predicate:

现在,调用上面的谓词:

Console.WriteLine(isValueOne.Invoke(1)); // -- returns true.

3) An anonymous method can also be assigned to a Predicate delegate type as below:

3) 匿名方法也可以分配给 Predicate 委托类型,如下所示:

Predicate<string> isUpper = delegate(string s) { return s.Equals(s.ToUpper());};
    bool result = isUpper("Hello Chap!!");

Any best practices about predicates?

关于谓词的任何最佳实践?

Use Func, Lambda Expressions and Delegates instead of Predicates.

使用 Func、Lambda 表达式和委托而不是谓词。

回答by parijat mishra

A delegate defines a reference type that can be used to encapsulate a method with a specific signature. C# delegate Life cycle:The life cycle of C# delegate is

委托定义了一种引用类型,可用于封装具有特定签名的方法。 C# 委托生命周期:C# 委托的生命周期

  • Declaration
  • Instantiation
  • INVACATION
  • 宣言
  • 实例化
  • 度假中

learn more form http://asp-net-by-parijat.blogspot.in/2015/08/what-is-delegates-in-c-how-to-declare.html

了解更多信息 http://asp-net-by-parijat.blogspot.in/2015/08/what-is-delegates-in-c-how-to-declare.html

回答by dexterous

Predicate falls under the category of generic delegates in C#. This is called with one argument and always return boolean type. Basically, the predicate is used to test the condition - true/false. Many classes support predicate as an argument. For e.g. list.findall expects the parameter predicate. Here is an example of the predicate.

谓词属于 C# 中的泛型委托类别。这是用一个参数调用的,并且总是返回布尔类型。基本上,谓词用于测试条件 - 真/假。许多类支持谓词作为参数。例如 list.findall 需要参数谓词。下面是谓词的一个例子。

Imagine a function pointer with the signature -

想象一个带有签名的函数指针 -

bool delegate myDelegate(T match);

bool 委托 myDelegate(T 匹配);

Here is the example

这是例子

Node.cs

节点.cs

namespace PredicateExample
{
    class Node
    {
        public string Ip_Address { get; set; }
        public string Node_Name { get; set; }
        public uint Node_Area { get; set; }
    }
}

Main class -

主课——

using System;
using System.Threading;
using System.Collections.Generic;

namespace PredicateExample
{
    class Program
    {
        static void Main(string[] args)
        {
            Predicate<Node> backboneArea = Node =>  Node.Node_Area == 0 ;
            List<Node> Nodes = new List<Node>();
            Nodes.Add(new Node { Ip_Address = "1.1.1.1", Node_Area = 0, Node_Name = "Node1" });
            Nodes.Add(new Node { Ip_Address = "2.2.2.2", Node_Area = 1, Node_Name = "Node2" });
            Nodes.Add(new Node { Ip_Address = "3.3.3.3", Node_Area = 2, Node_Name = "Node3" });
            Nodes.Add(new Node { Ip_Address = "4.4.4.4", Node_Area = 0, Node_Name = "Node4" });
            Nodes.Add(new Node { Ip_Address = "5.5.5.5", Node_Area = 1, Node_Name = "Node5" });
            Nodes.Add(new Node { Ip_Address = "6.6.6.6", Node_Area = 0, Node_Name = "Node6" });
            Nodes.Add(new Node { Ip_Address = "7.7.7.7", Node_Area = 2, Node_Name = "Node7" });

            foreach( var item in Nodes.FindAll(backboneArea))
            {
                Console.WriteLine("Node Name " + item.Node_Name + " Node IP Address " + item.Ip_Address);
            }

            Console.ReadLine();
        }
    }
}

回答by Shubham Khare

Simply -> they provide True/False values based on condition mostly used for querying. mostly used with delegates

简单 - >它们根据主要用于查询的条件提供真/假值。主要与代表一起使用

consider example of list

考虑列表示例

List<Program> blabla= new List<Program>();
        blabla.Add(new Program("shubham", 1));
        blabla.Add(new Program("google", 3));
        blabla.Add(new Program("world",5));
        blabla.Add(new Program("hello", 5));
        blabla.Add(new Program("bye", 2));

contains names and ages. Now say we want to find names on condition So I Will use,

包含姓名和年龄。现在说我们想在条件下找到名字所以我会使用,

    Predicate<Program> test = delegate (Program p) { return p.age > 3; };
        List<Program> matches = blabla.FindAll(test);
        Action<Program> print = Console.WriteLine;
        matches.ForEach(print);

tried to Keep it Simple!

试图保持简单!