我有一个如下的数据表,我想从其他类中选择重复的名称

Name    Class
Akbar   1B
Akbar   1B
Amar    1A
Amar    1C
Antoney 1A
Bindhu  1B
Bindhu  1D
John    1C
Raj     1B
Bindhu  2A


结果应如下

Amar    1A
Amar    1C
Bindhu  1D
Bindhu  1B
Bindhu  2A


在此先感谢您的指导



var dtStudents = new DataTable();
dtStudents.Columns.Add("StudentID", typeof(int));
dtStudents.Columns.Add("StudentName", typeof(string));
dtStudents.Columns.Add("Class", typeof(string));
dtStudents.Columns.Add("ContactNo", typeof(string));

DataRow drStudent = dtStudents.NewRow();

drStudent["StudentID"] = 1;
drStudent["StudentName"] = "Akbar";
drStudent["Class"] = "1B";
drStudent["ContactNo"] = "989878679";
dtStudents.Rows.Add(drStudent);

dtStudents.Rows.Add(new object[] { 2, "Akabr", "1B", "989777" });
dtStudents.Rows.Add(new object[] { 3, "Amar", "1A", "3453" });
dtStudents.Rows.Add(new object[] { 4, "Amar", "1C", "543534" });
dtStudents.Rows.Add(new object[] { 5, "Antoney", "1A", "54345" });
dtStudents.Rows.Add(new object[] { 6, "Bindhu", "1B", "53453" });
dtStudents.Rows.Add(new object[] { 7, "Bindhu", "1D", "3453453" });
dtStudents.Rows.Add(new object[] { 8, "John", "1C", "3245345" });
dtStudents.Rows.Add(new object[] { 9, "Bindhu", "2A", "5345345" });

var results =
    from d in dtStudents.AsEnumerable()
    select d;

dataGridView1.DataSource = results.CopyToDataTable<DataRow>();

最佳答案

var results = dtStudents.AsEnumerable()
    .GroupBy(
        x => x.Field<string>("StudentName"), // group by student name
        (k, xs) => xs.GroupBy(
            x1 => x1.Field<string>("Class"), // group by class
            (k1, xs1) => xs1.First())) // if there are duplicates, take only the first
    .Where(x => x.Count() >= 2) // remove if student only has one class
    .SelectMany(x => x); // flatten back to a single collection

dataGridView1.DataSource = results.CopyToDataTable<DataRow>();

10-08 09:18