Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq to compare two collections in C#

Tags:

c#

linq

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.

like image 668
DAK Avatar asked Dec 08 '22 23:12

DAK


1 Answers

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 }
like image 191
Anders Abel Avatar answered Dec 11 '22 13:12

Anders Abel