MAXE
MAXE

Reputation: 5142

LINQ grouping and aggregating data with conditions

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 = ...   // ???
        };

Upvotes: 6

Views: 253

Answers (2)

daryal
daryal

Reputation: 14929

var favorites = (from ProductFavorite pf in allFavorites
                             group pf by pf.ProductUid into distinctFavorites
                             select new ProductFavorite()
                {
                    Uid = Guid.NewGuid(),
                    ProductUid = distinctFavorites.Key,                    
                    IsFavorite = distinctFavorites.Any(p => p.IsFavorite == true),
                    IsLastUsed = distinctFavorites.Any(p => p.IsLastUsed == true),
                    LastUsedYear = distinctFavorites.Max(l => l.LastUsedYear) 
                });

Upvotes: 0

Rawling
Rawling

Reputation: 50144

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...")

Upvotes: 2

Related Questions