Reputation: 11
I have a table called TIME and there are multiple students in it. Sometimes, student A will have more than one entry in TIME. How do I print just the latest record for student A?
Upvotes: 1
Views: 1048
Reputation: 1380
You have to group the records by student entry time.
from r in StudentRecords
group r by r.StudentId into g
select new { StudentId = g.Key, MostRecentEntry = g.Max(e => e.EntryTime)}
since I don't know your schema, I've used some arbitrary names
Upvotes: 0
Reputation: 268255
void Main ()
{
var rows = new [] {
new Student { Name = "A", Timestamp = DateTime.Now.AddHours (-1) },
new Student { Name = "A", Timestamp = DateTime.Now.AddHours (-3) },
new Student { Name = "B", Timestamp = DateTime.Now.AddHours (4) },
new Student { Name = "B", Timestamp = DateTime.Now.AddHours (1) },
new Student { Name = "B", Timestamp = DateTime.Now }
};
var recentRows = from row in rows
group row by row.Name into studentRows
select studentRows.OrderByDescending (sr => sr.Timestamp).First ();
Console.WriteLine (recentRows);
}
class Student {
public string Name { get; set; }
public DateTime Timestamp { get; set; }
}
Upvotes: 0
Reputation: 8704
You want latest student A?.. Then may be you need something like this:
dataGridView.DataSource = students.GroupBy(s => s.Name).
Select(i => i.OrderByDescending(s => s.DateChanged).First());
I assume here that you can sort them by some parameter(i used DateChanged here..May be you have some incremental primary key or smth).
Upvotes: 2
Reputation: 8704
This sample uses Distinct to remove duplicate elements in a sequence of factors of 300.
public void Linq46()
{
int[] factorsOf300 = { 2, 2, 3, 5, 5 };
var uniqueFactors = factorsOf300.Distinct();
Console.WriteLine("Prime factors of 300:");
foreach (var f in uniqueFactors)
{
Console.WriteLine(f);
}
}
Result
Prime factors of 300:
2
3
5
See: http://msdn.microsoft.com/en-us/vcsharp/aa336761.aspx#distinct1
Upvotes: 0