1

I would like to re-use a linq-to-sql function I did, and everytime I will pass it another field to group by.

for example:

groupby(fieldX);
groupby(fieldY);

public void groupby(??? fieldName)
{
    return from rows in db....... group by fieldname
}

this was a pseudo

thanks!

Himberjack
  • 5,230
  • 13
  • 67
  • 109

2 Answers2

2

If I understand your question correctly, you're trying to recreate the LINQ Enumerable.GroupBy method itself.

You can thus achieve your desired result, without writing a whole new method, by doing:

var group1 = someEnumerable.GroupBy(o => o.fieldX);
var group2 = someEnuemrable.GroupBy(o => o.fieldY);
Joshua Rodgers
  • 5,018
  • 2
  • 28
  • 29
  • I want it to send it to the SQL... within the query itself. I dont want my application to calculate this – Himberjack Sep 01 '11 at 20:09
  • What are you using to access the database? Is this Entity Framework, LINQ to SQL, or some other technology? Regardless of the technology, if it returns the query back as an `IQueryable` the GroupBy method will still work on the `IQueryable` and will defer the group by to the database. – Joshua Rodgers Sep 01 '11 at 20:12
  • @Himberjack - If you are using Linq-To-SQL, it will be sent to the database as long as the `GroupBy` is on the DataContext. – vcsjones Sep 01 '11 at 20:13
2

Checkout this post. Probably you will need to mix code a little but you will find the GroupBy(string fieldName)

There described dynamically creating of the Lambda Expressions

Community
  • 1
  • 1
Samich
  • 27,359
  • 5
  • 63
  • 75