比较列表并在C#中返回匹配项 [英] Compare List and return matches in c#

查看:70
本文介绍了比较列表并在C#中返回匹配项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比较2个列表并返回匹配项的最快,最好的方法是什么. 只能进行一场比赛. List1包含来自数据库的动态数据.

What is the fastest and best way to compare 2 lists and return a match. Only one match is possible. List1 contains dynamic data from a database.

我现在的操作方式:

foreach (var item1 in List1)
{
   foreach (var item2 in List2 )
   {
       if(item2 == item1)
       string match = item1;
   }
}

我感觉可以更快地完成它.

I have a feeling like it can be done a lot faster.

推荐答案

使用 Enumerable.Intersect .

var matchItem = List1.Intersect(List2).First();

不太确定它比当前代码快多少,可以使用Stopwatch进行测量.但是在您当前的代码中,您应该在找到匹配项时中断内部循环和外部循环.像这样:

Not really sure how much it is faster to your current code, you can measure it using Stopwatch. But in your current code you should break your inner as well as outer loop on finding the match. Something like:

foreach (var item1 in List1)
{
    string match = null;
    foreach (var item2 in List2)
    {
        if (item2 == item1)
        {
            match = item1;
            break;
        }
    }
    if (match != null)
        break;
}

这篇关于比较列表并在C#中返回匹配项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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