65.9K
CodeProject is changing. Read more.
Home

Find Odds Out in a Generic List

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.86/5 (6 votes)

Oct 22, 2012

CPOL

1 min read

viewsIcon

11442

Find the Odds Out in A Generic List

Introduction

The below article provides the solution for picking up the Odds out From a Generic List.

Background

Everyone who worked on Generic Lists might have faced the issue of retrieving the odds out from the list.

So I'm posting the solution here:

Using the code

For demonstrating this I have created three Data Transfer Object classes namely Student, Subject, and StudentSubjects:

  • Student - Student is a class with details of student like Student ID and Name.
  • Subject - Subject is a class with details of Subjects like Subject ID and Subject Name.
  • StudentSubjects - StudentSubjects is a class where we map Student with a Subject.

The classes declaration is as follows:

public class Student
{
    public Int32 SID { get; set; } // Student ID
    public String SName { get; set; }
}

public class Subject
{
    public Int32 SubjectID { get; set; } // Subject ID
    public String SubjectName { get; set; }
}

public class StudentSubjects
{
    public Int32 SubjectID { get; set; } // Subject ID
    public Int32 SID { get; set; } // Student ID
}

Assume that AllStudentsList contains all Students.

List<StudentSubjects> StudentSubjectsList = new List<StudentSubjects>(); 

Assume that  StudentSubjectsList contains list of the Students having a particular Subject, say Physics.

Now I want of Students who are not having their study Subject as Physics.

For achieving the odds out I'm using Lambda Expression.

var PhysicsStudents = StudentSubjectsList.Select(T => T.SID).ToList(); 

In the above line I have created a implicitly typed variable PhysicsStudents and selecting Student IDs into it from the list.

List<Student> OddStudents = AllStudentsList.Where(T => !PhysicsStudents.Contains(T.SID)).ToList();

And this is the code that gives you the odds out from the Student List. Here we are selecting Students which are not in Physics Students List.

If both the Lists are of same type you can use the below code using the keyword Except.

Assume that you have two Lists as below:

List<Student> AllStudentsList = new List<Student>();
List<Student> PhysicsStudentsList = new List<Student>();

To fetch the Odds out we can use the below code:

List<Student> OddStudents = AllStudentsList.Except(PhysicsStudentsList).ToList();

History

This is my first article, if any concerns please help me in bringing it out better.