[英]How do I conditionally update List<Object> items using LINQ
如何使用 LINQ 有条件地更新List<object>
项目,我设法使用以下语法更新List<object>
所有项目:
var updatedList = sourceList.Select( x => { x.PropertyA = NewValue; return x; }).ToList();
var updatedList = sourceList.Select( x => {return x = x.PropertyA == SomeValue ? x1 : x;}).ToList();
You can either project it to a new collection using the .Select, or affect the original list using the .ForEach extension method.您可以使用 .Select 将其投影到新集合,或者使用 .ForEach 扩展方法影响原始列表。 Both are shown below, given an arbitrary condition.在给定任意条件的情况下,两者都如下所示。
class Program
{
static void Main(string[] args)
{
List<testClass> ogList = new List<testClass>();
bool testCondition = true;
//use the select to update and project to new collection
var updated =
ogList
.Select(x =>
{
if (testCondition)
x.testProp = 1;
return x;
}).ToList();
//use the foreach to update original collection
ogList.ForEach(x =>
{
if (testCondition)
x.testProp = 1;
});
}
}
public class testClass
{
public int testProp { get; set; }
}
You can use this code:您可以使用此代码:
sourceList.Where(w => w.CheckProperty == valueofProperty).Select(s => {
s.PropertyA = valueofPropertyA ;
s.PropertyB = valueofPropertyB;
return s;
}).ToList();
Hope this answer will help you.希望这个回答能帮到你。 So here I creating objects of my database, list of my db_table and table.所以在这里我创建了我的数据库的对象,我的 db_table 和表的列表。
private DB dbs = new DB();
List<tab1> lst = new List<tab1>();
tab1 tabobj = new tab1();
here you will get the list of data in your table在这里您将获得表格中的数据列表
lst = dbs.tab1.ToList();
````````````
updating the table
```````````
tabobj.c1 = "value";
tabobj.c2 = "value";
adding updated columns to table将更新的列添加到表
dbs.tab1.Add(tabobj);
save changes here在此处保存更改
dbs.SaveChanges();
data of updated table更新表的数据
lst = dbs.tab1.ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.