简体   繁体   中英

Linq to Compare two datatables and Filter data

I have two dataTables ,

     Id     Name
      1     Alex
      2     Hiro

and my second datatable is

      Field   |  1   |  1_Value  |  2     |  2_Value
      Salary  | 123.4|  Good     |  245   |  Bad
      CTC     | 25.4 |  Bad      |  300   |  good

First Table Id values 1, 2 are the column of second table. I wanna compare both table using the Id - column relation using linq and my expected filtered output should look like

      [{
        "Id" : 1 , "Name": "Alex",
         "data" : [123.4, 25.4] ,"values":["Good" ,"Bad"]},
        {
        "Id" : 2 , "Name": "Hiro",
         "data" : [245, 300] ,"values":["Bad","Good" ]}
        ]

My Code try is using foreach loops like

        if (ds.Tables[1].Rows.Count > 0)
                {
                    var comparisonDetail = (from DataRow dataRow in ds.Tables[1].Rows
                                            select new cls.MyBaseClass()
                                            {
                                                ID = Convert.ToInt64(dataRow["ID"]),
                                                Name= Convert.ToString(dataRow["Name"])  
                                            }

                                            ).ToList();
                    foreach (var vId  in  comparisonDetail)
                    {
                       foreach(var vRow in ds.Tables[2].Rows)
                       {
            vId.Data = vRow.value.

                       } 
                    }

How can I acheive this using c# linq? Help would be appreciated

You want to use join ( join clause (C# Reference) )

using(var c = DataBaseConnection())
{
 var data=from r in c.firstTable
          join st in c.SecondTable on r.Id equals st.FieldId
          select new
                 { 
                   // create return object
                 };
}

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