开发者

linq to object get element from list

开发者 https://www.devze.com 2023-03-07 14:06 出处:网络
List<PrpSubjects> objListSubjects= _objSubjectDal.GetAllSubjects(); ddlSubjects.DataSource = objListSubjects;
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();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号