Mike Turner
Mike Turner

Reputation: 471

dynamically specify select columns linq

Using linq, I'm trying to implement the following logic-

Iqueryable.Select(q=> new {
    if a then q.field1,q.field2,q.field3
    else if b then q.field1, q.field4
    else q.field5,q.field6,q.field7,q.field8
});

Any ideas for the best way to do this?

Upvotes: 0

Views: 967

Answers (2)

David L
David L

Reputation: 33833

You could certainly encapsulate this into a method that returns dynamic, although you lose your type safety and always with dynamic, a bit of performance.

public dynamic DynamicSelect(Expression<Func<Address, dynamic>> query)
{
    return Addresses.Select(query).Take(1).ToList();
}

You can then call it and retrieve data from it like so:

var result = DynamicSelect(q => new {q.Id, q.AddressLine1});
Console.WriteLine(result[0].Id);

When using DbSets, you can even take this a step further and genericize it:

public dynamic DynamicSelect<TEntity>(Expression<Func<TEntity, dynamic>> query)
{
    return context.DbSet<TEntity>.Select(query).Take(1).ToList();
}

Personally I'd ask yourself if this type of flexibility is really necessary. You're killing your type safety for a marginal increase in "flexibility".

Upvotes: 2

Jeferson Almeida
Jeferson Almeida

Reputation: 144

I think you can try something like this

        IQueryable query;  
        if (a)
            query.Select(q=> new {q.field1,q.field2,q.field3});
        else if (b)
            query.Select(q=> new {q.field1, q.field4});
        else
            .Select(q=> new {q.field5,q.field6,q.field7,q.field8});

Upvotes: 0

Related Questions