lsharma
lsharma

Reputation: 121

linq to object get element from list

List<PrpSubjects> objListSubjects  = _objSubjectDal.GetAllSubjects();
ddlSubjects.DataSource = objListSubjects;
ddlSubjects.DataBind();

_subjectName = objListSubjects...?

In _subjectName I want to fetch the subjectname from objListSubjects on basis of subjectid. The subject list has subjectid and subjectname columns.

the question is i have a list with 2 columns subjectid,subjectname... the method returns a list of subject now i want to fetch the subjectname by subjectid,,, i thght instead of querying the database again i thght to use linq on list to fetch the subject name.. i hope i am clear about my requirement

Upvotes: 0

Views: 612

Answers (3)

BitKFu
BitKFu

Reputation: 3697

Or, if you find the sql style better to read ;)

_subjectName = (from s in objListSubjects 
               where s.SubjectId == someId 
               select s.SubjectName).FirstOrDefault();

Upvotes: 0

Thomas Levesque
Thomas Levesque

Reputation: 292735

_subjectName = objListSubjects
               .Where(s => s.SubjectId == someId)
               .Select(s => s.SubjectName)
               .FirstOrDefault();

(will return null if there is no subject with the id someId)

Upvotes: 2

Botz3000
Botz3000

Reputation: 39660

_subjectName = objListSubjects.First(s => s.SubjectID == theIdYouAlreadyHave).SubjectName;

If you suspect that subject might not exist, you can use

objListSubjects.FirstOrDefault(s => s.SubjectID == id);

That will return null if it doesn't exist.

Upvotes: 0

Related Questions