Reputation: 67
I have the following Linq statement, which works totally fine:
query = query.OrderBy(m => m.MATERIAL_TXT.Where(mt => mt.LANG == "EN").FirstOrDefault().LTEXT);
Now I'm trying to make it dynamic by using the string based syntax from Linq.Dynamic:
query = query.OrderBy("MATERIAL_TXT.Where(LANG==\"EN\").FirstOrDefault().LTEXT");
But it throws the exception :
"No applicable aggregate method 'FirstOrDefault' exists"
It has to bedynamic so that it accepts other names instead of "MATERIAL_TXT".
What am I missing?
Upvotes: 3
Views: 1106
Reputation: 375
You can't use FirstOrDefault as string like that.
if you want to create dynamic orderBy try this :
Func<IQueryable<YourEntityType>, IOrderedQueryable<YourEntityType>> orderBy;
orderBy = x => x.OrderBy(m => m.MATERIAL_TXT.Where(mt => mt.LANG == "EN").FirstOrDefault().LTEXT);
Then you can use it like this :
orderBy(query);
for example you can use it in another method :
public List<YourEntityType> YourMethodName(Func<IQueryable<YourEntityType>, IOrderedQueryable<YourEntityType>> orderBy,IQueryable<YourEntityType> query=null)
{
query=query ?? GetYourEntityTypeList().AsQueryable();
return orderBy(query).ToList();
}
I Hope it will be useful .
Upvotes: 1
Reputation: 63722
According to the documentation:
A subset of the Standard Query Operators is supported for objects that implement IEnumerable. Specifically, the following constructs are permitted, where seq is an IEnumerable instance, predicate is a boolean expression, and selector is an expression of any type:
- seq.Where(predicate)
- seq.Any()
- seq.Any(predicate)
- seq.All(predicate)
- seq.Count()
- seq.Count(predicate)
- seq.Min(selector)
- seq.Max(selector)
- seq.Sum(selector)
- seq.Average(selector)
FirstOrDefault
isn't on the list, so it's reasonably safe to assume it isn't supported.
Upvotes: 1