C
C#2y ago
Halfbax

❔ Predicate in LINQ GroupBy

Hello, how can I replace item.Name with the predicate?
public static ObservableCollection<GroupInfo> Create<TData>(IEnumerable<TData> data, Expression<Func<TData, string>> predicate)
where TData : class
{
IEnumerable<GroupInfo> query = data
.GroupBy(item => item.Name.ToUpper())
.OrderBy(g => g.Key)
.Select(g => new GroupInfo(g.Key, g));

return new ObservableCollection<GroupInfo>(query);
}
public static ObservableCollection<GroupInfo> Create<TData>(IEnumerable<TData> data, Expression<Func<TData, string>> predicate)
where TData : class
{
IEnumerable<GroupInfo> query = data
.GroupBy(item => item.Name.ToUpper())
.OrderBy(g => g.Key)
.Select(g => new GroupInfo(g.Key, g));

return new ObservableCollection<GroupInfo>(query);
}
14 Replies
Halfbax
HalfbaxOP2y ago
I have tried to replace it with .GroupBy(item => predicate.ToUpper()), but the result is x instead of the string inside of item.Name.
Anton
Anton2y ago
predicate(item).ToUpper() why is it an expression? ef core?
Thinker
Thinker2y ago
Also regular IEnumerable<T> doesn't operate on Expression (?) Only IQueryable<T> operates on Expressions
Halfbax
HalfbaxOP2y ago
I have copied it from my generic ef methods. Seems to be a mistake
Anton
Anton2y ago
use iqueryable you also need expression expanding I don't know how this works, but there's a package I know that could help LinqKit
Halfbax
HalfbaxOP2y ago
This works?
Anton
Anton2y ago
pretty sure no
Thinker
Thinker2y ago
If it's not an Expression, it will work
Anton
Anton2y ago
but it's not gonna run on the db if you convert the query to ienumerable
Halfbax
HalfbaxOP2y ago
It wont run on ef I just want to convert and sort my current list It works Thanks for the help 🙂 If I convert it to iqueryable do I have to use the linqkit?
Anton
Anton2y ago
you use it to expand the expressions without that library it's nastier
Halfbax
HalfbaxOP2y ago
ah kk thanks 🙂
Lexaro
Lexaro2y ago
You can replace item.Name with the predicate argument
public static ObservableCollection<GroupInfo> Create<TData>(IEnumerable<TData> data, Expression<Func<TData, string>> predicate)
where TData : class
{
IEnumerable<GroupInfo> query = data
.GroupBy(predicate.Compile()
.Invoke)
.OrderBy(g => g.Key)
.Select(g => new GroupInfo(g.Key, g));

return new ObservableCollection<GroupInfo>(query);
}
public static ObservableCollection<GroupInfo> Create<TData>(IEnumerable<TData> data, Expression<Func<TData, string>> predicate)
where TData : class
{
IEnumerable<GroupInfo> query = data
.GroupBy(predicate.Compile()
.Invoke)
.OrderBy(g => g.Key)
.Select(g => new GroupInfo(g.Key, g));

return new ObservableCollection<GroupInfo>(query);
}
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server