我有一个数据表。只有满足条件时,才需要使用常量和其他列的值填充列的值。
以下是针对SQL Server的。
UPDATE table SET ColumnA = 'MyValue.' + ID WHERE SOURCE IN ('1', '2')
如何在C#中使用LINQ实现相同的目标?
我可以做这样的事情,但这将使我的where子句延伸。
var results = from myRow in table.AsEnumerable()
where myRow.Field<int>("SOURCE ") == 1 or myRow.Field<int>("SOURCE ") == 2
select myRow;
foreach (DataRow Row in results.Rows)
Row["ColumnA"] = 'MyValue.' + Row["ID"] ;
答案 0 :(得分:1)
您可以使用此Linq查询来更新数据表
List<int> lstSrc = new List<int> {1, 2};
table.AsEnumerable().Where(a => lstSrc.Contains(a.Field<int>("SOURCE")))
.Select(b => b["ColumnA"] = string.Concat("MyValue.", b["ID"]))
.ToList();
这将更新您的数据表列“ColumnA”
答案 1 :(得分:0)
var results = from myRow in table.AsEnumerable()
where new List<int> {1, 2}.Contains(myRow.Field<int>("SOURCE "))
select myRow;
答案 2 :(得分:0)
从概念上讲,这可以通过Join确保至少存在一个匹配来完成:
var query = from myRow in table.AsEnumerable()
join source in sourceFilters
on myRow.Field<int>("SOURCE") equals source
into sources
where sources.Any()
select myRow;
答案 3 :(得分:-1)
我可以这样做:
public class YourObject
{
public string Id {get;set;}
public string Source {get;set;}
}
void Main()
{
List<string> updateIds = new List<string>() {"1", "2"};
List<YourObject> oldList = new List<YourObject>()
{
new YourObject { Id = "1", Source = "test1" },
new YourObject { Id = "2", Source = "test2" },
new YourObject { Id = "3", Source = "test3" },
new YourObject { Id = "4", Source = "test4" }
};
List<YourObject> newList = oldList.Where(i => updateIds.Contains(i.Id))
.Select(j => {
j.Id="'MyValue.'" + j.Id;
return j;
}).ToList();
}
答案 4 :(得分:-1)
1. dtNewLCM.AsEnumerable().Where(row => row.Field<string>("leafClass")=="0")
.Select(b => b["leafClass"] = "MyValue1.")
.ToList();