Lambda C # expression help

If I use a lambda expression like the following

// assume sch_id is a property of the entity Schedules
public void GetRecord(int id)
{
    _myentity.Schedules.Where(x => x.sch_id == id));
}

I suppose (although not verified), I can rewrite this using an anonymous inline function using something like

_jve.Schedules.Where(delegate(Models.Schedules x) { return x.sch_id == id; });

My question is how would I rewrite this in a normal (not built-in) function and still pass the id parameter.

+3
source share
3 answers

The short answer is that you cannot make it a standing function. In your example, it is idactually stored in closure .

: , , id, , -. - , , . , "" , . . .

, :

public class IdSearcher
{
     private int m_Id; // captures the state...
     public IdSearcher( int id ) { m_Id = id; }
     public bool TestForId( in otherID ) { return m_Id == otherID; }
}

// other code somewhere...
public void GetRecord(int id)
{
    var srchr = new IdSearcher( id );
    _myentity.Schedules.Where( srchr.TestForId );
}
+7

, ,

public void GetRecord(int id)
{
    _myentity.Schedules.Where(x => MyMethodTooLongToPutInline(x, id));
}
private bool MyMethodTooLongToPutInline(Models.Schedules x, int id)
{
    //...
}
+1

You will need to save the identifier somewhere. This is done for you with a closure , which basically looks like creating a separate temporary class with a value and method.

0
source

Source: https://habr.com/ru/post/1721415/


All Articles