Linq比较C#中的两个集合 [英] Linq to compare two collections in C#

查看:812
本文介绍了Linq比较C#中的两个集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用嵌套的"for"循环比较当前正在使用的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;
        }
    }
}
}

我想将AcademicYearCollection中的代码"与OrgCollection&中的"AcademicYearCode"属性进行比较如果相同,则将其添加到下拉列表"ddlYear"中.

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".

谢谢.

推荐答案

您可以在LINQ中进行操作,这会提供较短的代码.要知道它是否更有效,您必须对其进行概要分析.我认为linq的join运算符内部使用某种哈希桶,这些哈希桶应具有更好的性能,尤其是在集合很大的情况下.您当前的解决方案是O(N ^ 2),如果选项数量增加,该值会迅速降低.

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 }

这篇关于Linq比较C#中的两个集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆