Group by in Linq

Group by in LINQ

Absolutely - you basically want:

var results = from p in persons
group p.car by p.PersonId into g
select new { PersonId = g.Key, Cars = g.ToList() };

Or as a non-query expression:

var results = persons.GroupBy(
p => p.PersonId,
p => p.car,
(key, g) => new { PersonId = key, Cars = g.ToList() });

Basically the contents of the group (when viewed as an IEnumerable<T>) is a sequence of whatever values were in the projection (p.car in this case) present for the given key.

For more on how GroupBy works, see my Edulinq post on the topic.

(I've renamed PersonID to PersonId in the above, to follow .NET naming conventions.)

Alternatively, you could use a Lookup:

var carsByPersonId = persons.ToLookup(p => p.PersonId, p => p.car);

You can then get the cars for each person very easily:

// This will be an empty sequence for any personId not in the lookup
var carsForPerson = carsByPersonId[personId];

How to use LINQ group by with where clause

Try below code,

        var list = travelars.GroupBy(x => new { x.From, x.To }).ToList().Select(e => new { 
MaleCount = e.Count(g => g.Gender == "M"),
FemaleCount = e.Count(g => g.Gender == "F"),
ChildCount = e.Count(g => g.Gender == "C"),
});

C# LINQ Group by

var topTen = flights.
GroupBy(g => g.Origin).
Select(g => new { Origin = g.Key, AvgDelay = g.ToList().Average(d => d.DepartureDelay) }).
OrderByDescending(o => o.AvgDelay).
Take(10);

LINQ Group By and select collection

I think you want:

items.GroupBy(item => item.Order.Customer)
.Select(group => new { Customer = group.Key, Items = group.ToList() })
.ToList()

If you want to continue use the overload of GroupBy you are currently using, you can do:

items.GroupBy(item => item.Order.Customer, 
(key, group) => new { Customer = key, Items = group.ToList() })
.ToList()

...but I personally find that less clear.

Group By in LINQ with a particular column

You can do that in C#. Since every Fund_ID has a unique Fund_Name, it is safe to group by both columns:

var grouped = (from f in data
group f by new { F.Fund_ID, F.Fund_Name } into grouping
select new Class1()
{
Fund_ID = grouping.Key.Fund_ID,
Fund_Name = grouping.Key.Fund_Name,
Details = grouping.Select(x=> new Class2()
{ Amount = x.Amount, Date = x.Dated }).ToList()
}).ToList();

Assumes you have classes:

public class Class1
{
public string Fund_ID { get; set; }
public string Fund_Name { get; set; }
public List<Class2> Details { get; set; }
}

public class Class2
{
public string Date { get; set; }
public string Amount { get; set; }
}

How to select last record in a LINQ GroupBy clause

You can order you items

Mains.GroupBy(l => l.ContactID)
.Select(g=>g.OrderByDescending(c=>c.ID).FirstOrDefault())
.ToList()

Linq Group by and get all values for a specific string rule returning all columns

In another words Grouping the model by Email all Passed must be yes, then I know for this Certification that specific Email completed with success.

Sounds like, at its most basic

var listOfEmailsThatPassed = p
.GroupBy(s => s.Email)
.Where(g => g.All(pt => pt.Passed == "Yes"))
.Select(g => g.Key)
.ToList()

You didn't say what type Passed is; i assumed string but if it's a bool g.All(pt => pt.Passed).

Grouping can be tricky to get your head round, but think of it like a list-of-list-of-participant, you have a .Where( that acts on a grouping g, which is a list of participants, so you want All the participants pt in the grouping to have passed

For a list of participants (I've skipped detail like the course name):

   john@a.com Yes
john@a.com Yes
fred@b.com Yes
fred@b.com No

After grouping it looks like

   g => g.Key: john@a.com   g: [ john@a.com Yes, john@a.com Yes] 
g => g.Key: fred@b.com g: [ fred@b.com Yes, fred@b.com No]

So you can use Where to act on each of these two rows, and g is itself a (sub)list of Participants that all share the same Key (email), so you ask that g.All(participant => some predicate).. and that's where you test that Passed == "Yes" as your predicate. If anyone is Passed == "No" then the All will return false and the Where will exclude them from the results

After Where'ing it looks like:

   g => g.Key: john@a.com   g: [ john@a.com Yes, john@a.com Yes] 

It's still a grouping, so perhaps you have to select the email:

.Select(g => g.Key).ToList()

this will churn out a List<string> of the emails that passed

C# LINQ - Group List by a property then select by different groups

Something like this:

 var result = list
.GroupBy(item => item.A)
.SelectMany(group => string.IsNullOrEmpty(group.Key)
? group as IEnumerable<ABC>
: new ABC[] {group.First()})
.ToList();

The trick here is that we should return collection: either entire group or a collection (array) with the First item only.

You can get rid of grouping and flatten to have a faster version which, however, exploits side effect:

 HashSet<string> uniqueA = new HashSet<string>(); 

var result = list
.Where(item => string.IsNullOrEmpty(item.A) || uniqueA.Add(item.A))
.ToList();

LINQ - GroupBy Year/Month

Try using this one. See comments for possible fixes.

var testQUERY = await _context.Calculation
.AsNoTracking()
.Where(x => x.PaymentDate != null)
.Select(x => new { PaymentDate = x.PaymentDate.Value, Row=x }) // pre-select non-null payment date
.Where(x => x.PaymentDate > DateTime.UtcNow.AddMonths(-4)) // this should go after the grouping, as it might include from just part of the month
.GroupBy(x => new { x.PaymentDate.Year, x.PaymentDate.Month})
.Select(grp=> new { grp.Key.Year, grp.Key.Month, Count = grp.Count()) // flatten group and calculate aggregates
.ToListAsync();

C# LINQ GroupBy to convert a List to a group with one property as List of values

After GroupBy, use ToDictionary:

source.GroupBy(x => x.Name)
.ToDictionary(x => x.Key, x => x.Select(e => e.Value).ToList());

This yields a Dictionary<string, List<string>> where the keys are the names and the values are lists made up of projecting each element to a string under that specific group.

I assume that Value is a string for example purposes only but in reality, it doesn't really matter as the solution remains the same.



Related Topics



Leave a reply



Submit