1

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
KC Jane
  • 11
  • 2
  • Similar questions: http://stackoverflow.com/questions/3530148/selecting-custom-distinct-items-from-a-list-using-linq, http://stackoverflow.com/questions/2537823/distinct-by-property-of-class-by-linq – Yakimych Mar 28 '11 at 11:47

4 Answers4

2

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).

0x49D1
  • 8,505
  • 11
  • 76
  • 127
0

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

0x49D1
  • 8,505
  • 11
  • 76
  • 127
  • 1
    This will not help because we're asked to *get the latest*, not to *remove duplicates*. You can't instruct `Distinct` which rows are ‘better’. – Dan Abramov Mar 28 '11 at 11:53
  • Yes..Thats why ive added another answer after re-reading the question. – 0x49D1 Mar 28 '11 at 12:27
0
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; }
}
Dan Abramov
  • 264,556
  • 84
  • 409
  • 511
0

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

Nasmi Sabeer
  • 1,370
  • 9
  • 21