Linq Order By, Group by and Order by Each Group

Linq order by, group by and order by each group?

Sure:

var query = grades.GroupBy(student => student.Name)
.Select(group =>
new { Name = group.Key,
Students = group.OrderByDescending(x => x.Grade) })
.OrderBy(group => group.Students.First().Grade);

Note that you can get away with just taking the first grade within each group after ordering, because you already know the first entry will be have the highest grade.

Then you could display them with:

foreach (var group in query)
{
Console.WriteLine("Group: {0}", group.Name);
foreach (var student in group.Students)
{
Console.WriteLine(" {0}", student.Grade);
}
}

LINQ to SQL - order by, group by and order by each group with skip and take

You can take another approach using Max instead of ordering each group and taking the first value. After that you can order by max grade, name (in case two students have the same max grade) and grade:

var query = c.Customers
.GroupBy(s => s.Name, (k, g) => g
.Select(s => new { MaxGrade = g.Max(s2 => s2.Grade), Student = s }))
.SelectMany(s => s)
.OrderBy(s => s.MaxGrade)
.ThenBy(s => s.Student.Name)
.ThenByDescending(s => s.Student.Grade)
.Select(s => s.Student)
.Skip(toSkip)
.Take(toTake)
.ToList();

All these methods are supported by EF6 so you should get your desired result.

linq group by, order by

list1.GroupBy(item => new { Counter = item.Counter, SrvID = item.SrvID })
.Select(group => new {
ID = group.First().ID,
Counter = group.Key.Counter,
SrvID = group.Key.SrvID,
FirstName = group.First().FirstName})
.OrderBy(item => item.ID);

How to group by and order by a collection using linq?

You have a problem of understanding here. If you do a grouping you'll have a property to work with: the key.

I am taking the northwind database with the products table here as reference. If you Group products by CategoryId Products.GroupBy (p => p.CategoryID) you can then append OrderBy of course. But the only property you can order by afterwards is the key:

//p.Key is the CategoryId after which you grouped by
Products.GroupBy (p => p.CategoryID).OrderBy (p => p.Key)

What you need to do is, is select the grouping and work with it:

Products.GroupBy (p => p.CategoryID).Select (p => p.OrderBy (x => x.UnitPrice))

If you want to flatten your result use SelectMany:

Products.GroupBy (p => p.CategoryID).SelectMany (p => p.OrderBy (x => x.UnitPrice))

EDIT
To clarify the Select/SelectMany issue: This is what you'll get using Select. A return type of IOrderedQueryable<IOrderedEnumberable<Products>>. In essence a List inside a List.

Sample Image

If you use SelectMany(), you flatten this List inside a List into one List

Sample Image

LINQ group by then order groups of result

Try

rawData.Provider.CreateQuery<PDFDocument>(qb.rootExperession)
.AsEnumerable()
.OrderByDescending(d => d.UploadDate)
.GroupBy(d => d.ShortCode)
.SelectMany(g => g)
.ToList();

This should

  • Order the items by upload date (descending so newest first)
  • Then group them by short code - so within each group the items are still sorted
  • The groups are still in descending order, so no need to order again
  • Finally concatenate the results into a single list

If performance is an issue you many be better off doing

rawData.Provider.CreateQuery<PDFDocument>(qb.rootExperession)
.AsEnumerable()
.GroupBy(d => d.ShortCode)
.Select(g => g.OrderByDescending(d => d.UploadDate))
.OrderByDescending(e => e.First().UploadDate)
.SelectMany(e => e)
.ToList();

which sorts the contents of each group separately rather than sorting everything first and then grouping.

How to use LINQ to group by and order by certain column

Based on the new edited question, I have this:

var ordered = dataT.AsEnumerable()
.GroupBy(en => new { Name = en.Field<string>("Name"), Place = en.Field<string>("Place") })
.OrderBy(eng => eng.Min(en => en.Field<DateTime>("DateTimeCombined")))
.ThenBy(eng => eng.Key.Name).ThenBy(eng => eng.Key.Place)
.SelectMany(eng => eng.OrderBy(en => en.Field<DateTime>("DateTimeCombined")), (eng, en) => en)
.CopyToDataTable();

C# LINQ group collection by attribute then sort each group by explicit order defined by a list

Here is a solution I have found:


using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
public static void Main()
{
var countryOrder =new List<string> { "UK", "KE", "AU", "USA"};

var data = new List<ExampleDataClass> {
new ExampleDataClass {
Name = "Alice",
Country = "UK",
Age = 30,
},

new ExampleDataClass {
Name = "Bob",
Country = "KE",
Age = 20,
},

new ExampleDataClass {
Name = "Charlie",
Country = "UK",
Age = 30,
},

new ExampleDataClass {
Name = "Alice",
Country = "KE",
Age = 40,
},

new ExampleDataClass {
Name = "Bob",
Country = "AU",
Age = 50,
},

new ExampleDataClass {
Name = "David",
Country = "USA",
Age = 25,
}
};

var reducedData = data.GroupBy(x => x.Name)
.Select(g => g.OrderBy(item => countryOrder.IndexOf(item.Country)).First())
.ToList();

foreach (ExampleDataClass item in reducedData)
{
Console.WriteLine(string.Format("Name: \"{0}\", Country: \"{1}\", Age: {2}", item.Name, item.Country, item.Age));
}
}
}

class ExampleDataClass
{
public string Name { get; set; }

public string Country { get; set; }

public int Age { get; set; }
}

Output

Name: "Alice", Country: "UK", Age: 30
Name: "Bob", Country: "KE", Age: 20
Name: "Charlie", Country: "UK", Age: 30
Name: "David", Country: "USA", Age: 25

link to a dotnetfiddle https://dotnetfiddle.net/6geHtk

Linq OrderBy then GroupBy - group by unexpectedly changes order of list

Instead of grouping an ordered collection, group the collection first, and then select the record with the highest ID for each of the groups. GroupBy is not guaranteed to preserve the order in each group in LINQ to SQL - it depends on your database server.

var list = db.Actions.Where(z => z.RunId == RunId).GroupBy(c => new
{
c.ActionName,
c.MachineNumber,
})
.Select(y => y.OrderByDescending(z => z.ActionId).FirstOrDefault()).ToList();


Related Topics



Leave a reply



Submit