Sergey Aslanov
Sergey Aslanov

Reputation: 683

How to compare generics in where clause in linq query

I want to compare string of structs for now

public Entity GetByPropertyValue<ValueType>(string propertyName, ValueType value)
{
    var contact = (from contacts in OrganizationContext.CreateQuery("contact")
                 where (ValueType)contacts[propertyName] == value
                 select contacts).FirstOrDefault();

    return contact;
}

but the problem is:

Operator '==' cannot be applied to operands of type 'ValueType' and 'ValueType'

If do it otherwise

where object.Equals((ValueType)contacts[propertyName], value)

it will not work unfortunately

System.NotSupportedException: Invalid 'where' condition. An entity member is invoking an invalid property or method.

Upvotes: 2

Views: 392

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062820

This is probably a scenario where a manual expression-tree construction is warranted. I can't test this without your code, but something like:

public Entity GetByPropertyValue<T>(string propertyName, T value)
{
    var p = Expression.Parameter(typeof(Entity));
    var body = Expression.Equal(
        Expression.PropertyOrField(p, propertyName),
        Expression.Constant(value, typeof(T)));
    var lambda = Expression.Lambda<Func<Entity, bool>>(body, p);

    return OrganizationContext.CreateQuery("contact").Where(lambda).FirstOrDefault();
}

the last line might also be possibly rewritten:

return OrganizationContext.CreateQuery("contact").FirstOrDefault(lambda);

Note that while this might look verbose, this is actually what the C# compiler is generating anyway for an expression-tree based predicate; so: it doesn't have any impact on the actual performance of the code - it is still doing the same thing.

Upvotes: 1

Related Questions