Robert J. Robert J. - 2 months ago 23
C# Question

Create reusable LINQ Expression

I have a list on SharePoint, where I am trying to load fields for this list like following:

var lists = context.Web.Lists;
context.Load(lists, n => n.Include(x => x.Title,
x => x.Fields.Include(
z => z.Title,
z => z.InternalName,
z => z.TypeDisplayName)));
context.ExecuteQuery();


The following part of the code I use quite often in my code, while working with other lists:

x => x.Fields.Include(
z => z.Title,
z => z.InternalName,
z => z.TypeDisplayName)


I would like to know if there is a way how to simplify inserting this
.Include
statement in my code (so that in case I will have to add more properties in the future, I dont have to rewrite all my code everywhere but only in one place).

I have tried to create custom LINQ Extension, but it failed as it is probably expecting sort of a
Expression<Func<T,Y>>
(I guess).

Any help regarding this matter would be more than appreciated!

Answer

Since the Load method expects an Expression<Func<T, object>>, and lists is presumably IQueryable<Something> you can use something like:

public static Expression<Func<IQueryable<Something>, Object>> IncludeCommonFields()
{
    // since the method returns an Expression, this will actually
    // get compiled to an expression tree
    return input => input.Fields.Include(z => z.Title, 
                                         z => z.InternalName, 
                                         z => z.TypeDisplayName);
}

Evaluating the function should create a new instance of the expression tree:

var lists = context.Web.Lists;
context.Load(lists, n => n.Include(x => x.Title,
                                   IncludeCommonFields());
context.ExecuteQuery();

If it's invoked often, you might also choose to instantiate it only once:

static readonly Expression<Func<IQueryable<Something>, Object>> _commonIncludes 
   = input => input.Fields.Include(z => z.Title, 
                                        z => z.InternalName, 
                                        z => z.TypeDisplayName);

context.Load(lists, n => n.Include(x => x.Title,
                                   _commonIncludes);