ghost media
ghost media

Reputation: 25

How to remove an element in the list that has the same string but lower startDate

How to remove an element in the list that has the same string but lower startDate.Time?

Let's say you have a list that looks like this:

Datetime Date        String Name
07.06.2019 10:16:00, Test 
07.06.2019 11:16:00, Test 
07.06.2019 12:16:00, Test 
07.06.2019 13:16:00, Test 
07.06.2019 18:16:00, Test1 
07.06.2019 19:16:00, Test1 
07.06.2019 20:16:00, Test1 
07.06.2019 21:16:00, Test1 
07.06.2019 22:16:00, Test2 
07.06.2019 23:16:00, Test2

Given that the DateTime.Date is identical, I want to keep only the DateTime.Date that has the latest timestamp for each string in the list.

How can I achieve this?

My implementation :

List.OrderByDescending(x => x.Datetime).GroupBy(x => 
x.Datetime.Date).Select(x => x.First()).ToList();

But this doesn't consider that the string should be different as if Test and test1 have the same Datetime.Date value, but the Test string has a later timestamp, then it would remove the Test1 element, which is not desired.

Upvotes: 0

Views: 52

Answers (3)

NetMage
NetMage

Reputation: 26946

Since you said you wanted to get the latest on each date for each Name, I would suggest:

var ans = list.GroupBy(i => new { i.Date.Date, i.Name }).Select(ig => ig.OrderByDescending(i => i.Date.TimeOfDay).First()).ToList();

Upvotes: 1

akg179
akg179

Reputation: 1559

Suppose the class with DateTime and string properties looks like this:

public class MyClass
{
    public string Text { get; set; }
    public DateTime Date { get; set; }
}

Then the LINQ which u can use is something like this:

var newList = List.GroupBy(l => l.Text).Select(g => new MyClass { Text = g.Key, Date = g.Max(i => i.Date)}).ToList();

This will give you a filtered list as per your requirement.

Upvotes: 1

ilkerkaran
ilkerkaran

Reputation: 4364

You can do it via using Max;

var result = List.GroupBy(x => x.Name)
                .Select(i => new MyList { Name = i.Key, DateTime = i.Max(j => j.DateTime).Date })
                .ToList();

Upvotes: 1

Related Questions