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 questio开发者_高级运维n 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
_subjectName = objListSubjects
.Where(s => s.SubjectId == someId)
.Select(s => s.SubjectName)
.FirstOrDefault();
(will return null
if there is no subject with the id someId
)
_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.
Or, if you find the sql style better to read ;)
_subjectName = (from s in objListSubjects
where s.SubjectId == someId
select s.SubjectName).FirstOrDefault();
精彩评论