How about this
var allYears = AcademicYear.RetrieveAll().ToDictionary(y => y.Code, y.Name); ListItem match = null; foreach(var year in Org.RetrieveDistinctYear()) { if (allYears.HasKey(year.AcademicYearCode) { match = new ListItem( allYears[year.AcademicYearCode], year.AcademicYearCode); break; } } if (match != null) { ddlYear.Items.Insert(0, match); }
Using Dictionary here provides superior performance, and the further the results of Org.RetrieveDistinctYear match, the greater the benefit. If the results of RetrieveDistinctYear are often short or the match is at the top, the overhead of creating a dictionary will make the code invisible.
EDIT
Or this approach
var allYears = AcademicYear.RetrieveAll().ToDictionary(y => y.Code, y.Name); var matchingCode = Org.RetrieveDistinctYear() .Select(y = y.AcademicYearCode) .FirstOrDefault(code => allYears.HasKey(code)); if (!string.IsEmptyOrWhitespace(matchingCode)) { ddlYear.Items.Insert(0, new ListItem( allYears[matchingCode], matchingCode)); }
source share