是否有一种方法来做以下使用LINQ?

foreach (var c in collection)
{
    c.PropertyToSet = value;
}

为了澄清,我希望遍历集合中的每个对象,然后更新每个对象的属性。

我的用例是我在一篇博客文章上有一堆评论,我想迭代一篇博客文章上的每一条评论,并将博客文章上的datetime设置为+10小时。我可以用SQL来做,但我想把它保留在业务层。


当前回答

假设我们有如下数据,

var items = new List<string>({"123", "456", "789"});
// Like 123 value get updated to 123ABC ..

如果我们想修改列表并将列表中的现有值替换为修改后的值,那么首先创建一个新的空列表,然后通过调用每个列表项上的修改方法来遍历数据列表,

var modifiedItemsList = new List<string>();

items.ForEach(i => {
  var modifiedValue = ModifyingMethod(i);
  modifiedItemsList.Add(items.AsEnumerable().Where(w => w == i).Select(x => modifiedValue).ToList().FirstOrDefault()?.ToString()) 
});
// assign back the modified list
items = modifiedItemsList;

其他回答

你可以使用LINQ将你的集合转换为数组,然后调用array . foreach ():

Array.ForEach(MyCollection.ToArray(), item=>item.DoSomeStuff());

显然,这将不适用于结构体或内建类型(如整数或字符串)的集合。

我正在做这个

Collection.All(c => { c.needsChange = value; return true; });

我假设您希望在查询中更改值,以便为其编写函数

void DoStuff()
{
    Func<string, Foo, bool> test = (y, x) => { x.Bar = y; return true; };
    List<Foo> mylist = new List<Foo>();
    var v = from x in mylist
            where test("value", x)
            select x;
}

class Foo
{
    string Bar { get; set; }
}

但如果你是这个意思,那就不是舒坦了。

不,LINQ不支持大规模更新。唯一更短的方法是使用ForEach扩展方法-为什么IEnumerable上没有ForEach扩展方法?

实际上我找到了一个扩展方法,可以很好地完成我想要的

public static IEnumerable<T> ForEach<T>(
    this IEnumerable<T> source,
    Action<T> act)
{
    foreach (T element in source) act(element);
    return source;
}