Dynamic Linq select first in groups after GroupBy

c# dynamic-linq linq linq-to-sql

Question

I think I've read every post on this subject but still can't seem to get this to work. I want to duplicate the following GroupBy with dynamic Linq. I've tried this Dynamic GroupBy but can't seem to get the First().

var result = mydata
    .GroupBy(g => g.ID)
    .Select(z => z.First())
    .Select("new (ID, Field1, Field2)");

The GroupBy needs to be dynamic. I need the first row of the grouped field. So..

ID:1, Field1:W, Field2:L 
ID:1, Field1:A, Field2:B 
ID:2, Field1:A, Field2:B 
ID:2, Field1:C, Field2:D 

Should end up being:

ID:1, Field1:W, Field2:L 
ID:2, Field1:A, Field2:B 
OR
ID:1, Field1:A, Field2:B 
ID:2, Field1:C, Field2:D 
1
2
5/23/2017 12:16:03 PM

Accepted Answer

I solved it by adding to DynamicQueryable

public static object First(this IQueryable source)
        {
            if (source == null) throw new ArgumentNullException("source");
            return source.Provider.Execute(
                Expression.Call(
                    typeof(Queryable), "First",
                    new Type[] { source.ElementType },
                    source.Expression));
        }

Above not required..but added anyway for consistency.

And adding to IEnumerableSignatures

void First()

Query becomes:

var result = mydata
    .GroupBy("ID", "it")
    .Select("it.First()")
    .Select("new (ID, Field1, Field2)");
4
5/29/2015 11:25:05 PM


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