Question: Sorry for the title being a little vague, couldn't think of a good one.

I have a list of objects that holds some maximum and minimum limit values along with a timestamp.

To illustrate, my grid used to show the contents of that list could be like this (very simplified):

```
LimitMin | LimitMax | Start Time
1            2        08:00
1            2        08:01
1            2        08:03
2            5        08:05
2            5        08:06
2            5        08:10

```

Right now, I just do a select distinct, to get the distinct limits and add them to a list, like this:

```
var limitdistinct = printIDSPC.Select(x => new { x.LimitMin, x.LimitMax }).Distinct();

```

But I would like to get the timestamp as well, where the limits changed (08:05 in the example above). I cannot seem to figure out, how to accomplish this. I thought about how Distinct actually works behind the scenes, and if you could somehow get the timestamp from the select statement. Do I have to go through the entire list in a foreach loop, and compare the values to see where it changed?

Any help?

Answer: 
The trick here is to use GroupBy instead of Distinct. You could then either get the minimum timestamp for each limits pair:

```
items
    .GroupBy(x => new { x.LimitMin, x.LimitMax })
    .Select(x => new { 
        x.Key.LimitMin, 
        x.Key.LimitMax, 
        MinStartTime = x.Min(y => y.StartTime) 
    });

```

or, as GroupBy preserves the order of the original items, get the first timestamp for each:

```
items
    .GroupBy(x => new { x.LimitMin, x.LimitMax })
    .Select(x => new { 
        x.Key.LimitMin, 
        x.Key.LimitMax, 
        FirstStartTime = x.First().StartTime 
    });

```
One solution would be to group by min/max, then order by start time and finally select the first time value:

```
var list = new List<Foo>
{
    new Foo { LimitMin = 1, LimitMax = 2, StartTime = TimeSpan.Parse("08:00") },
    new Foo { LimitMin = 1, LimitMax = 2, StartTime = TimeSpan.Parse("08:01") },
    new Foo { LimitMin = 1, LimitMax = 2, StartTime = TimeSpan.Parse("08:03") },
    new Foo { LimitMin = 2, LimitMax = 5, StartTime = TimeSpan.Parse("08:05") },
    new Foo { LimitMin = 2, LimitMax = 5, StartTime = TimeSpan.Parse("08:06") },
    new Foo { LimitMin = 2, LimitMax = 5, StartTime = TimeSpan.Parse("08:10") },
};

var tmp = list
    .GroupBy(z => new { z.LimitMin, z.LimitMax })
    .Select(z =>
        new
        {
            Time = z.OrderBy(z2 => z2.StartTime).First().StartTime,
            Min = z.Key.LimitMin,
            Max = z.Key.LimitMax
        })
    .ToList();

```