How to create a dynamic LINQ query in C # with possible multiple group clauses?

I have been a programmer for several years, but I am new to LINQ and C #, so forgive me if my question sounds particularly stupid.

I hope someone can point me in the right direction. My task is to come up with a way to create a dynamic multiple group at the request of linq in a C # script using a shared list as the source.

For example, let's say I have a list containing several items with the following words Structure:

FieldChar1 - character FieldChar2 - character FieldChar3 - character FieldNum1 - numeric FieldNum2 - numeric 

In a nutshell, I want to be able to create a LINQ query that will summarize FieldNum1 and FieldNum2, grouped by one, two or all three FieldChar fields that will be defined in
depending on user requirements, as well as the choice of FieldChar fields in the same query.

I have dynamic.cs in my project that includes the GroupByMany extension method, but I have to admit that I'm really not sure how to use them. I can get the desired results if I use a query with a wired query group, but not dynamically.

Apologizing for any erroneous nomenclature, I am new to this language, but any advice would be most welcome.

Many thanks

Alex

+6
c # linq group-by linq-to-objects
source share
2 answers

Here is an example of GroupBy . Say we have a simple class:

 public class Person { public string Name { get; set; } public int Age { get; set; } public char Sex { get; set; } } 

Then you can use GroupBy as follows:

 var people = new List<Person> { new Person { Name = "Joe", Age = 30, Sex = 'M' }, new Person { Name = "Liz", Age = 22, Sex = 'F' }, new Person { Name = "Jim", Age = 22, Sex = 'M' }, new Person { Name = "Alice", Age = 30, Sex = 'F' }, new Person { Name = "Jenny", Age = 22, Sex = 'F' } }; var groups = people.GroupBy(p => p.Age); foreach (var group in groups) { foreach (var person in group) Console.WriteLine(person.Name + " - " + person.Age); } 

Regarding grouping by several properties, see the following: http://weblogs.asp.net/zeeshanhirani/archive/2008/05/07/group-by-multiple-columns-in-linq-to-sql.aspx
LINQ TO DataSet: Multiple Data Table Groups

Basically, this is the same syntax with an anonymous type, for example:

 var groups = people.GroupBy(p => new { p.Age, p.Sex }); 

Note that you can use multiple OrderBy s:

 var query = people.OrderBy(p => p.Age).ThenBy(p => p.Sex); //You can have unlimited ThenBy's 

Also note that the result of the last GroupBy statement and the result of this OrderBy statement are NOT the same.

+1
source share

GroupBy (groupByName + "" + groupByDirection, new {})

So you can pass in groupByName and groupByDirection, when you go, you can see something like

GroupBy ("lastName desc", new {})

or

GroupBy ("firstName asc", new {})

0
source share

All Articles