Reputation: 11
I have dataset looks like this:
FileName Date
ABC - 01/10/16
DBC - 01/11/16
ZYX - 03/10/16
ABX2 - 01/10/17
IOS - 01/09/17
How can I group them into a list of groups of months while ensuring that the year is taken into account in the clause?
I'm currently using a LINQ Query is creating groups by month but not including the year, so I have a group of ABC, ZYX and ABX2. even though ABX2 was a 2017 report but the same month so should be in a different group.
I've been trying different ways of doing this but none of have been successful as of yet.
var newList = from x in list
group x
by x.Properties.LastModified.Value.Month into lastMod
where lastMod.Count() > 1
select lastMod;
Once I have them in separate groups, I will find out which one was written last and save that and remove the rest. I'm quite stuck and been on this issue for half day. would appreciate fresh eyes on it.
Upvotes: 0
Views: 2003
Reputation: 3764
I can't test this at the moment but I think grouping by an anonymous type that contains both the month and year should do it.
var newList = from x in list
group x
by new {x.Properties.LastModified.Value.Month, x.Properties.LastModified.Value.Year} into lastMod
where lastMod.Count() > 1
select lastMod;
Upvotes: 1
Reputation: 726599
You can group by a composite year-month key, like this:
var newList = list
.Where(x => x.Properties.LastModified.HasValue)
.GroupBy(x => new {
x.Properties.LastModified.Value.Month
, x.Properties.LastModified.Value.Year
})
.Where(g => g.Count() > 1);
You need to ensure that LastModified
has non-null value before accessing its Value
property.
Upvotes: 3