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 = ... // ???
};
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...")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With