Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Find Odds Out in a Generic List

0.00/5 (No votes)
22 Oct 2012 1  
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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here