EF Select records distinct by one field from Entity

c# dynamic-linq entity-framework group-by linq

Question

I need to "translate" this code sample:

using var db = new MyDbContext();
var simple_linq = db.USERS.GroupBy(u => u.id_employee).Select(u => u.FirstOrDefault()).ToList(); //it's worked fine for me

to same code with Dynamic LINQ. I've try:

var dynamic_linq = db.USERS.GroupBy(groupBy, "it").Select("it"); // but I need Dynamic LINQ

I receive a USERS objects in dynamic_linq (very important for me), but don't know how can I get unique USERS, don't know how can I use FirstOrDefault() function in Dynamic LINQ, don't know how can I convert my result to List. Don't know any other solution.

I've also try to use DistinctBy() from MoreLinq library, but it can not usage with dynamic expressions.

Any ideas?

1
0
11/5/2019 7:45:00 PM

Popular Answer

When using System.Linq.Dynamic.Core, you should be able to use this code:

var users = new[] { new { id_employee = 1, name = "a"  }, new { id_employee = 1, name = "b"  } }.AsQueryable();

var simple_linq = users.GroupBy(u => u.id_employee).Select(u => u.FirstOrDefault()).ToList();
simple_linq.Dump();

var dynamic_linq = users.GroupBy("id_employee", "it").Select("it.FirstOrDefault()");
dynamic_linq.Dump();

enter image description here

1
11/22/2019 8:32:10 AM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow