I want to compare two collections in C# that I'm currently doing using nested "for" loop. is there a way in Linq to do the same which will be quicker and more efficient? here is my current code which works perfectly just looking for an efficient way:
OrgCollection myYears = Org.RetrieveDistinctYear();
if (myYears.Count > 0)
{
AcademicYearCollection allYears = AcademicYear.RetrieveAll();
for (int i = 0; i < myYears.Count; i++)
{
for (int j = 0; j < allYears.Count; j++)
{
if (myYears[i].AcademicYearCode == allYears[j].Code)
{
ddlYear.Items.Insert(0, new ListItem(allYears[j].Name,allYears[j].Code));
break;
}
}
}
}
I want to compare "Code" from AcademicYearCollection with the "AcademicYearCode" property in OrgCollection & if it is the same then add it in the Dropdownlist "ddlYear".
Thanks in advance.
You can do it in LINQ, which gives shorter code. To know if it is more efficient or not you would have to profile it. I think that linq's join operator uses some kind of hash buckets inernally which should give better performance, especially if the collections are large. Your current solution is O(N^2) which will quickly degrade if the number of options increases.
OrgCollection myYears = Org.RetrieveDistinctYear();
AcademicYearCollection allYears = AcademicYear.RetrieveAll();
var items = from y in myYears
join ay in allYears
on y.Code equals ay.AcademicYearCode
select new { ay.Name, ay.Code }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With