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

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

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

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


当前回答

我的2便士:-

 collection.Count(v => (v.PropertyToUpdate = newValue) == null);

其他回答

我已经尝试了一些变化,我一直回到这个家伙的解。

http://www.hookedonlinq.com/UpdateOperator.ashx

同样,这是别人的解。但我已经将代码编译成一个小库,并经常使用它。

我将把他的代码粘贴在这里,以防他的网站(博客)在未来的某个时候不复存在。(没有什么比看到一个帖子说“这是你需要的确切答案”更糟糕的了,点击,然后是死网址。)

    public static class UpdateExtensions {

    public delegate void Func<TArg0>(TArg0 element);

    /// <summary>
    /// Executes an Update statement block on all elements in an IEnumerable<T> sequence.
    /// </summary>
    /// <typeparam name="TSource">The source element type.</typeparam>
    /// <param name="source">The source sequence.</param>
    /// <param name="update">The update statement to execute for each element.</param>
    /// <returns>The numer of records affected.</returns>
    public static int Update<TSource>(this IEnumerable<TSource> source, Func<TSource> update)
    {
        if (source == null) throw new ArgumentNullException("source");
        if (update == null) throw new ArgumentNullException("update");
        if (typeof(TSource).IsValueType)
            throw new NotSupportedException("value type elements are not supported by update.");

        int count = 0;
        foreach (TSource element in source)
        {
            update(element);
            count++;
        }
        return count;
    }
}



int count = drawingObjects
        .Where(d => d.IsSelected && d.Color == Colors.Blue)
        .Update(e => { e.Color = Color.Red; e.Selected = false; } );

虽然你特别要求一个LINQ解决方案,这个问题很老了,但我发布了一个非LINQ解决方案。这是因为LINQ (= 语言集成查询)用于对集合进行查询。所有linq方法都不修改底层集合,它们只是返回一个新的集合(或者更准确地说是一个指向新集合的迭代器)。因此,无论你做什么,例如使用Select都不会影响底层集合,你只是获得一个新的集合。

当然,您可以使用ForEach(顺便说一下,这不是LINQ,而是List<T>上的扩展)。但是这里实际上使用了foreach,但是使用了lambda表达式。除此之外,每个LINQ方法都在内部迭代你的集合,例如通过使用foreach或for,然而它只是对客户端隐藏它。我不认为这更具可读性或可维护性(考虑在调试包含lambda-expressions的方法时编辑代码)。

说到这里,不应该使用LINQ来修改集合中的项目。更好的方法是你在问题中已经提供的解决方案。使用经典循环,您可以轻松迭代集合并更新其中的项目。事实上,所有这些解决方案都依赖于List。每一个都没有什么不同,但从我的角度来看很难理解。

所以你不应该在那些你想要更新集合元素的情况下使用LINQ。

我正在做这个

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

假设我们有如下数据,

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;

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

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