如何根据.net中的另一个数据表删除一个数据表行?

时间:2016-10-22 14:03:36

标签: c# asp.net .net datatable

我有一个名为dtFirst的数据表,如下所示

Fieldname              Newvalue

antenastructure        12
slno                   2
servicelevel
powersupply

另一个数据表为dtMaster

Mastertabe          Masterfield          infoid      zvalue     qvalue

M_seq               antenastructure       123          
M_seq               slno                  1      
M_seq               servicelevel          133
M_seq               powersupply           154
M_seq               azimheight            124

我想要的是,如果dtMaster Fieldname dtFirst不包含Newvalue,我希望从servicelevel中删除行,即此处我想删除行包含{ {1}}和powersupply。这两个是大数据表,其中我发布了小部分

2 个答案:

答案 0 :(得分:1)

这是我手机上输入的伪代码:

var rowsWithoutVals = dtFirst.Rows.Select("newValues = ''");

for(int i = dtMaster.Rows.Count - 1; i > -1;i--) {

 foreach (var emptyItem in rowsWithoutVals) {
  if (emptyItem[0] == dtMaster[i][1]) {
    dtMaster.Rows.RemoveAt[i];
    break;
   }
 }
}

答案 1 :(得分:1)

看看是否有效

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            DataTable dtFirst = new DataTable();
            dtFirst.Columns.Add("Fieldname", typeof(string));
            dtFirst.Columns.Add("Newvalue", typeof(int));
            dtFirst.Columns["Newvalue"].AllowDBNull = true;

            dtFirst.Rows.Add(new object[] {"antenastructure", 12});
            dtFirst.Rows.Add(new object[] {"slno", 2});
            dtFirst.Rows.Add(new object[] {"servicelevel"});
            dtFirst.Rows.Add(new object[] {"powersupply"});

            string[] dtFirstValidRows = dtFirst.AsEnumerable().Where(x => x.Field<int?>("Newvalue") != null).Select(x => x.Field<string>("Fieldname")).ToArray();

            DataTable dtMaster = new DataTable();
            dtMaster.Columns.Add("Mastertabe", typeof(string));
            dtMaster.Columns.Add("Masterfield", typeof(string));
            dtMaster.Columns.Add("infoid", typeof(int));
            dtMaster.Columns["infoid"].AllowDBNull = true;
            dtMaster.Columns.Add("zvalue", typeof(int));
            dtMaster.Columns["zvalue"].AllowDBNull = true;
            dtMaster.Columns.Add("qvalue", typeof(int));
            dtMaster.Columns["qvalue"].AllowDBNull = true;

            dtMaster.Rows.Add(new object[] {"M_seq", "antenastructure", 123});          
            dtMaster.Rows.Add(new object[] {"M_seq", "slno", 1});          
            dtMaster.Rows.Add(new object[] {"M_seq", "servicelevel", 133});          
            dtMaster.Rows.Add(new object[] {"M_seq", "powersupply", 154});          
            dtMaster.Rows.Add(new object[] {"M_seq", "azimheight", 124});

            dtMaster = dtMaster.AsEnumerable().Where(x => dtFirstValidRows.Contains(x.Field<string>("Masterfield"))).CopyToDataTable();
        }
    }
}