简体   繁体   中英

Using Linq for comparison of two Datatables

I am developing a C# ASP.NET web application. 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:

itemid, itemdept, itemdescription

Table2:

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.

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

I have read up a little on Linq, but can't find anything exactly like this scenario. Could I use Linq to accomplish such a thing? 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. 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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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