Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/273.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/29.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用LINQ更新数据表_C#_Asp.net_Visual Studio 2010_Linq - Fatal编程技术网

C# 使用LINQ更新数据表

C# 使用LINQ更新数据表,c#,asp.net,visual-studio-2010,linq,C#,Asp.net,Visual Studio 2010,Linq,我有两个具有相同标识列的数据表。我想用另一个表中的其他列值更新一个表中的一列值。例如: 以下是两个表格: 表1: ID Name Amount ------ ------- --------- 1 AA 0 2 BB 0 3 CC 0 表2

我有两个具有相同标识列的数据表。我想用另一个表中的其他列值更新一个表中的一列值。例如:

以下是两个表格:

表1:

       ID         Name           Amount
     ------      -------        ---------
        1          AA             0
        2          BB             0
        3          CC             0
表2:

       ID        Amount
     ------    ---------
        1        5000
        2        6000
        3        7000            
我想要的数据表如下所示:

可取的:

       ID         Name           Amount
     ------      -------        ---------
        1          AA             5000
        2          BB             6000
        3          CC             7000

我不想用for循环。如何使用LINQ实现此结果?

您可以使用join语句:

from item1 in table1
join item2 in table2 on item1.ID equals item2.ID
select new YourType { ID = item1.ID, Name = item1.Name, Amount = item2.Amount }

这里考虑表1为“dTababl 1”和表2为DTTABLE 2:

DTTable1.AsEnumerable().Join(DTTable2.AsEnumerable(), 
                     dt1_Row => dt1_Row.ItemArray[0],
                     dt2_Row => dt2_Row.ItemArray[0],
                     (dt1_Row, dt2_Row) => new { dt1_Row, dt2_Row }).ToList() 
                     .ForEach(o => o.dt1_Row.SetField(2, o.dt2_Row.ItemArray[1]));

我只是把这个贴在这里供将来参考

如果要使用DTBLTOUPDATEFORM中的值更新dtblToUpdate,但需要连接多个列,则此操作似乎有效:

dtblToUpdate.Rows.Cast<DataRow>().Join(dtblToUpdateFrom.Rows.Cast<DataRow>(),
            r1 => new { p1 = r1["ColToJoinOn1"], p2 = r1["ColToJoinOn2"] },
            r2 => new { p1 = r2["ColToJoinOn1"], p2 = r2["ColToJoinOn2"] },
            (r1, r2) => new { r1, r2 }).ToList()
            .ForEach(o => o.r1.SetField("ColToUpdate", o.r2["ColToUpdateFrom"]));

另外,当一个表缺少“金额”列时,另一个选项请参见本文。您可以在一列上联接这些表,并获得一个新的DataTable,其中两个表之间有所有唯一的列:

我不喜欢在web上看到的任何示例,因此下面是我的示例

        DataTable dt = new DataTable();
        dt.Columns.Add("Year");
        dt.Columns.Add("Month");
        dt.Columns.Add("Views");
        for (int year = 2011; year < 2015; year++)
        {
            for (int month = 1; month < 13; month++)
            {
                DataRow newRow = dt.NewRow();
                newRow[0] = year;
                newRow[1] = month;
                newRow[2] = 0;
                dt.Rows.Add(newRow);
            }
        }

        dataGridView1.DataSource = dt;

        //if using Lambda 
        //var test = dt.AsEnumerable().Where(x => x.Field<string>("Year") == "2013" && x.Field<string>("Month") == "2").ToList();

        var test = (from x in dt.AsEnumerable()
                    where x.Field<string>("Year") == "2013"
                    where x.Field<string>("Month") == "2"
                    select x).ToList();

         var records = from p in dt.AsEnumerable()
                            where p.Field<string>("Year") == "2013" && p.Field<string>("Month") == "2"
                            select new
                            {
                                Views = p.Field<string>("Views")//,
                                //Month = p.Field<string>("Month")
                            };
                        foreach (var record in records)
                        {
                            //Console.WriteLine(string.Format("{0}. {1}  ({2})", record.Views, record.Month, record.Views));
                            thisCount = Convert.ToInt32(record.Views);
                            thisCount++;
                        }
        test[0][2] = thisCount.ToString();

        dt.AcceptChanges();

        //if writing to sql use  dt.SubmitChanges() instead
DataTable dt=newdatatable();
dt.列。添加(“年度”);
dt.列添加(“月份”);
dt.列。添加(“视图”);
对于(国际年份=2011年;年份<2015年;年份++)
{
对于(整数月=1;月<13;月++)
{
DataRow newRow=dt.newRow();
newRow[0]=年份;
newRow[1]=月份;
新行[2]=0;
dt.Rows.Add(newRow);
}
}
dataGridView1.DataSource=dt;
//如果使用Lambda
//var test=dt.AsEnumerable()。其中(x=>x.Field(“年”)==“2013”和&x.Field(“月”)==“2”).ToList();
var test=(从dt.AsEnumerable()中的x开始)
其中x.Field(“年份”)=“2013”
其中x.Field(“月”)=“2”
选择x).ToList();
var记录=从p到dt.AsEnumerable()
其中p.Field(“年”)=“2013”和p.Field(“月”)=“2”
选择新的
{
视图=p.字段(“视图”)/,
//月=p.字段(“月”)
};
foreach(记录中的var记录)
{
//WriteLine(string.Format(“{0}.{1}({2})”,record.Views,record.Month,record.Views));
thiscont=Convert.ToInt32(record.Views);
thisCount++;
}
测试[0][2]=thiscont.ToString();
dt.AcceptChanges();
//如果要写入sql,请改用dt.SubmitChanges()

再次声明不希望使用for循环的任意注释。它确实提出了一个问题:为什么不您希望我们在不展示您尝试过的内容的情况下为您编写它吗?此外,LINQ通常用于创建新的集合/视图,而不会在现有集合/视图中产生副作用。For或foreach似乎足够合理,可以使用。我已经使用For循环编写了代码。这就是为什么我提到不要使用for循环。我想知道如何使用LINQ?这对您来说可能是显而易见的,但对其他任何人来说都不是。请在您的问题中包含类似的信息(以及相关示例)。=)+1,但您为不再使用DataTable提供了一个很好的理由。太难看了。@John:谢谢。我将保留并遵循您的建议,以备将来使用。@thevan我知道这是旧的,但我已经用一些测试代码更新了我的答案,以表明它确实更新了该列。
dtblToUpdate before update:
1.1 - nothing
2.1 - nothing
3.1 - nothing
dtblToUpdate after update:
1.1 - something
2.1 - something
3.1 - nothing
        DataTable dt = new DataTable();
        dt.Columns.Add("Year");
        dt.Columns.Add("Month");
        dt.Columns.Add("Views");
        for (int year = 2011; year < 2015; year++)
        {
            for (int month = 1; month < 13; month++)
            {
                DataRow newRow = dt.NewRow();
                newRow[0] = year;
                newRow[1] = month;
                newRow[2] = 0;
                dt.Rows.Add(newRow);
            }
        }

        dataGridView1.DataSource = dt;

        //if using Lambda 
        //var test = dt.AsEnumerable().Where(x => x.Field<string>("Year") == "2013" && x.Field<string>("Month") == "2").ToList();

        var test = (from x in dt.AsEnumerable()
                    where x.Field<string>("Year") == "2013"
                    where x.Field<string>("Month") == "2"
                    select x).ToList();

         var records = from p in dt.AsEnumerable()
                            where p.Field<string>("Year") == "2013" && p.Field<string>("Month") == "2"
                            select new
                            {
                                Views = p.Field<string>("Views")//,
                                //Month = p.Field<string>("Month")
                            };
                        foreach (var record in records)
                        {
                            //Console.WriteLine(string.Format("{0}. {1}  ({2})", record.Views, record.Month, record.Views));
                            thisCount = Convert.ToInt32(record.Views);
                            thisCount++;
                        }
        test[0][2] = thisCount.ToString();

        dt.AcceptChanges();

        //if writing to sql use  dt.SubmitChanges() instead