Reputation: 448
Hey i got a list having many records inside, there are 3 DateTime inside (nullable). What i need is to get a LINQ expression determining which one of this three is the latest then select that record and check again. Here is the code how i created the List.
List<ActivityJoinUserTopicVote> ActivityList = new List<ActivityJoinUserTopicVote>();
foreach (var p in postdate)
{
ActivityList.Add(new ActivityJoinUserTopicVote(p.R_Posted, p.Forum_id, p.R_Posted_By, p.R_Message, p.Reply_ID, p.Topic_ID, p.User));
}
foreach (var v in votedate)
{
ActivityList.Add(new ActivityJoinUserTopicVote(v.data, v.Topic_ID, v.vote, v.Member_ID, v.Vote_Member_ID));
}
foreach (var t in topicdate)
{
ActivityList.Add(new ActivityJoinUserTopicVote(t.T_date, t.Forum_id, t.T_Originator, t.T_Replies, t.T_ukaz, t.Topic_ID, t.User, t.T_Url, t.T_subject));
}
return ActivityList;
Before returning the ActivityList i need it to determine which one was the most recent and sort it this way. Maybe i could do this somehow while creating the list? The problem is i got 3 different columns inside i need to check in (R_Posted, data and T_date)
Upvotes: 0
Views: 189
Reputation: 45947
replace
return ActivityList;
with
return ActivityList.OrderByDescending(x => x.data.HasValue ? x.data : ( x.R_Posted.HasValue ? x.R_Posted : x.T_date)).ToList();
or
return ActivityList.OrderByDescending(x => new DateTime?[]{ x.data, x.R_Posted, x.T_date}.Max()).ToList();
to return the ActivityList
sorted by the date fields descending
Upvotes: 2
Reputation: 30022
Helper:
private long MaxOfThreeDate(DateTime? date1, DateTime? date2, DateTime? date3)
{
long max1 = Math.Max(date1.GetValueOrDefault().Ticks, date2.GetValueOrDefault().Ticks);
return Math.Max(max1, date3.GetValueOrDefault().Ticks);
}
Usage:
return ActivityList.OrderByDescending(x => MaxOfThreeDate(x.data, x.R_Posted, x.T_date)).ToList();
Upvotes: 3
Reputation: 874
You can get the most recent one using this
var list = ActivityList.OrderByDescending(x=>x.Date).First();
Upvotes: 1