Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ grouping and aggregating data with conditions

Tags:

c#

linq

I have some problems understanding a way to get the correct result from my LINQ query.

Let me first define the entity ProductFavorite

public class ProductFavorite
{
    public Guid Uid {get; set;}

    public Guid ProductUid {get; set;}

    public bool IsFavorite {get; set;}

    public bool IsLastUsed {get; set;}

    public int LastUsedYear {get; set;}
}

I have an IEnumerable of some favorites products, named allFavorites, containing objects made in the way I wrote before.

This "list" can contain elements with duplicates ProductUid, because it is build from different data sources.

And again: the items in the "list" have at least IsFavorite = true OR IsLastUsed = true.

I want to create, using LINQ of course, a resulting list of ProductFavorite objects, but grouping the items by ProductUid, and also grouping the three properties as follows:

IsFavorite will be true only if one of the grouped items has this property set to true

IsLastUsed will be true only if one of the grouped items has this property set to true

LastUsedYear will be the maximum value of LastUsedYear of the grouped items

I've tried the next syntax, but I'm not sure it can give me what I want:

var favorites = 
        from ProductFavorite pf in allFavorites
        group pf by pf.ProductUid into distinctFavorites
        select new ProductFavorite()
        {
            Uid = Guid.NewGuid(),
            ProductUid = distinctFavorites.Key,
            LastYearUsed = distinctFavorites.Max(l => l.LastYearUsed) // ???,
            IsFavorite = ...,  // ???
            IsLastUsed = ...   // ???
        };
like image 367
MAXE Avatar asked Aug 24 '12 12:08

MAXE


1 Answers

Your LastYearUsed (or LastUsedYear?) line looks OK. For the last two you'll want

IsFavorite = distinctFavorites.Any(l=>l.IsFavourite),
IsLastUsed = distinctFavorites.Any(l=>l.IsLastUsed)

(assuming you mean "any one of the items has it set to true", not "exactly one of the items...")

like image 91
Rawling Avatar answered Oct 10 '22 04:10

Rawling