I may have function calls like this :

foo(**new {x.ID,x.Name}**);

and LINQ:

(IQueryable<SomeTableName>).where(x=>x.ID>1).select(x=>**new {x.ID,x.Name}**);

Is it possible to replace the "new {x.ID,x.Name}" part with a function, expression or variable, so I can change from time to time, in only 1 place? Thank you.

I know I can make an Expression, which be used inside LINQ only

public static Func<SomeTableName, Object> Select_RS_Food = x => new { x.ID,x.Name };

but I also want to use for normal anonymous object creating. Like:

foo(CreateMyObject(x));

Update

Current:

return new { myTable.ID, myTable.Name};
//And
db.SomeTable.Select (x=> new { myTable.ID, myTable.Name));

Expect:

return SomeMagicCode;
//And
db.SomeTable.Select (x=> SomeMagicCode);
有帮助吗?

解决方案

You could define a helper class like this to allow you to specify only some of the generic type parameters when creating a Func<T, R>:

public static class Funk<T>
{
    public static Func<T, R> Make<R>(Func<T, R> func)
    {
        return func;
    }
}

And use it like this:

var selector = Funk<SomeTableName>.Make(x => new {x.ID, x.Name});
var result = db.SomeTable.Where(x => x.ID>1).Select(selector);

This takes advantage of type inference to determine the return type, so you only have to define the input type (SomeTableName). The var keyword makes the selector variable implicitly typed, you won't have to specify Func<SomeTableName, _AnonymousType1_>. You can now reuse selector in multiple queries.

You will not be able to save this as property or field of a class, however, because implicit typing is not supported in type members. If you want to be able to reuse this selection function, you must use a named type or perhaps dynamic—but I wouldn't expect this to work with any current ORM.

For the other lambda expressions (x => x.ID == 1 and x => x.ID > 1), there are no anonymous types involved so you can simply do this:

public static Func<SomeTableName, bool> IDEquals1 = x => x.ID == 1;
public static Func<SomeTableName, bool> IDGreaterThan1 = x => x.ID == 1;

But by the way, if your using an ORM like entity framework, you probably need to use an Expression instead. Maybe something kind of like this:

public static Expression<Func<T, bool>> IDEquals1 = x => x.ID == 1;

Or even this:

public interface IHasID 
{
    int ID { get; }
}

public SomeTableName : IHasID { ... }

public static Expression<Func<T, bool>> IDEquals1<T>() where T : IHasID
{
     return x => x.ID == 1;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top