Reputation: 3761
I have a list of objects with the following properties
public class Client
{
Id Guid,
FromDate datetime
}
List of Clients
List<Clients> clients = new List<Clients>();
There are many of the same Ids in this list with different FromDates. How can I get a list of the Id and the min FromDate for each Id?
So for example:
Id FromDate
1 2015-01-01
1 2016-01-01
2 2015-02-02
2 2015-12-31
I want to end up with a list with the following:
Id FromDate
1 2015-01-01
2 2015-02-02
Upvotes: 0
Views: 132
Reputation: 1196
Clients.GroupBy(client => client.Id, client => client)
.Select(times => times.OrderBy(client => client.FromDate).First())
Upvotes: 0
Reputation: 3968
There are many different ways two of them are
Distinct
You have to implement your own IEqualityComparer<Client>
(https://msdn.microsoft.com/en-us/library/bb338049.aspx)
and than you can call:
IEnumerable<Client> noduplicates = products.Distinct(new ClientComparer());
GroupBy
var result = clients
.GroupBy(c => c.Id)
.Select(g => new { Id = g.Key, FromDate = g.Min(c => c.FromDate) });
var result = from c in clients
group c by new { id = c.Id } into g
select new { id = g.Key, FromDate = g.Min(c => c.FromDate) };
Upvotes: 0