简体   繁体   English

使用Linq比较两个数据表

[英]Using Linq for comparison of two Datatables

I am developing a C# ASP.NET web application. 我正在开发C#ASP.NET Web应用程序。 I have data being pulled from two databases. 我有从两个数据库中提取的数据。 One is the database that holds all of our actual data, the second is to be used so that users of the site can save "favorites" and easily find this data later. 第一个是保存我们所有实际数据的数据库,第二个将被使用,以便站点的用户可以保存“收藏夹”并在以后轻松地找到这些数据。 The databases have the following columns: 数据库具有以下列:

Table1: 表格1:

itemid, itemdept, itemdescription

Table2: 表2:

userid, itemid, itemdept, itemdescription

If the item is present in table2 (the user has already added it), I want to mark the item as removable if it comes up again in a search, and addable if it has is not yet in their favorites. 如果该项目存在于table2中(用户已经添加了该项目),那么我想将该项目标记为可移动(如果它在搜索中再次出现),并且可添加(如果尚未添加到他们的收藏夹中)。

I've got data from both pulled into datatables so I can compare them, but I feel that using a nested foreach loops will be too tedious as the query is set to return a max of 300 results. 我已经将两者中的数据都放入了数据表中,以便可以对其进行比较,但是我觉得使用嵌套的foreach循环会太乏味,因为查询被设置为最多返回300个结果。 Also to do that, I have to put a bool value in one of the tables to mark that it was found, so this seems messy. 为此,我必须在其中一个表中放入一个bool值以标记已找到它,因此这看起来很混乱。

I have read up a little on Linq, but can't find anything exactly like this scenario. 我已经阅读了一些有关Linq的内容,但是找不到与这种情况完全相同的东西。 Could I use Linq to accomplish such a thing? 我可以用Linq完成这样的事情吗? Below is an (admittedly crude) image of the search results page that may help get a better grasp on this. 以下是搜索结果页面的图像(一定很粗糙),可以帮助您更好地掌握这一点。 In the real deal, the Add and Remove links will be imagebuttons. 实际上,添加和删除链接将是图像按钮。

网站布局

Forgot to ever post the solution to this one, but I went with the HashSet setup, with one loop to compare. 忘记将解决方案发布到该解决方案上了,但是我选择了HashSet设置,并进行了一个比较。 Thank you everyone for your comments. 谢谢大家的评论。

if (User.Identity.IsAuthenticated)
{
    DataColumn dc = new DataColumn("isMarked", System.Type.GetType("System.Int32"));
    ds.Tables[0].Columns.Add(dc);
    string[] strArray = ds.Tables[0].AsEnumerable().Select(s => s.Field<string>("itemid")).ToArray<string>();
    HashSet<string> hset = new HashSet<string>(strArray);
    foreach (DataRow dr in ds.Tables[0].Rows)
    {
         if (hset.Contains(dr["itemid"].ToString().Trim()))
             dr[3] = 1;
         else
             dr[3] = 0;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM