简体   繁体   中英

I need help grouping my data using Linq

I have the following object:

internal class AlbumImage
{
    internal string AlbumName { get; set; }
    internal string ImagePath { get; set; }
    internal DateTime DateTaken { get; set; }
}

With that, I have a List:

private List<AlbumImage> _albumImages;

I would like to group this list based on the Date Taken. The idea is that for each element, the Date Taken will be checked against a specific date (pre-defined), so for the sake of example, suppose we use the date Jan 1, 1980.

I would like to group my data as follows:

1 month

2 months

3 months

4 months

5 months

6 months

7 months

8 months

9 months

10 months

11 months

12 months

18 months

24 months

36 months

48 months

etc.

The idea is that after one year, the groupings change to a 6-months basis.

So going back to my date of 1980, any AlbumImages elements that have a date taken of 1 month or less from the date Jan 1, 1980, they should be in the 1 month grouping. Any AlbumImages elements that have a date taken of more than 1 month but 2 or less from the date Jan 1, 1980, they should be in the 2 months grouping. Etc ...

Is this simple to do in Linq ???

It is definitely simple to do with LINQ:

var specificDate = new DateTime(1980, 1, 1);
var results = (from x in input
              group x by GetGroup(x, specificDate) into g
              select new {
                  Time = g.Key, 
                  Images = g.ToList()
              }).ToList();

Of course I assumed you already have a method called GetGroup(DateTime date, DateTime startDate) which follows logic you've described: returns 1,2,3,4,...,12,18,24,..., which has nothing to do with LINQ and you should be able to write it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM