1

Hi guys i have two lists of the class Student

List<Student> group1= new List<Trade>();
List<Student> group2= new List<Trade>();
public class Student
        {
            public string First_Name{ get; set; }
            public string Surname{ get; set; }
            public string Age{ get; set; }
        }

i would like to do a join that enables me to see those that are only in 1 group.
ideal output being a datatable with column 1 showing those that only in group1 and column2 representing those only in group2 any help would be really appreciated. I am struggling to get my head around joins

Rahul Singh
  • 21,585
  • 6
  • 41
  • 56
Jon
  • 123
  • 7
  • 2
    You can't assign the `List` of `Trade` to `List` of `Student`. – Hamlet Hakobyan Dec 21 '14 at 16:42
  • You probably don't need a join here, which is probably why you're having trouble understanding how to do the join. I would wager that Rahul's answer is what you need, making this question a duplicate of http://stackoverflow.com/q/18099054/397817 . Also: in a large school it would not be at all unusual to have two students with the same forename, surname and age. You should consider assigning a unique ID to each student. – Stephen Kennedy Dec 21 '14 at 16:58
  • yes i have applied Rahuls answer to good effect using a unique string ID. thanks – Jon Dec 21 '14 at 17:14

2 Answers2

0

Use Except:-

var onlyInGroup1 = group1.Except(group2);
var onlyInGroup2 = group2.Except(group1);

Please note, since Student is a complex type, you need to implement IEqualityComparer<Student>.

Also, I missed your list initialization, as pointed by @Hamlet, it should be something like this:-

List<Student> group1= new List<Student>();
List<Student> group2= new List<Student>();
Rahul Singh
  • 21,585
  • 6
  • 41
  • 56
  • Thanks Rahul - perhaps i didn't explain correctly. i want to do a full join on the two lists and get the differences – Jon Dec 21 '14 at 16:46
  • @Jon - Why you need `Join` here? Can you show any sample input\output you are expecting? – Rahul Singh Dec 21 '14 at 17:00
  • thanks a lot just looking at IEqualityComparer. The Except worked great when i built strings of the info as opposed to classes. – Jon Dec 21 '14 at 17:04
  • @You in case of strings, default comparer will be used, you need to implement `IEqualityComparer` yourself for complex types such as Student. – Rahul Singh Dec 21 '14 at 17:06
0

you could iterate thru group1 and see if group2 contains a match to group1

foreach (Student student in group1)
 {
  if (group2.Contains(student.First_Name))
   {
    //logic goes here
   }
 }
SuncoastOwner
  • 263
  • 2
  • 9