是否有一种方法来做以下使用LINQ?
foreach (var c in collection)
{
c.PropertyToSet = value;
}
为了澄清,我希望遍历集合中的每个对象,然后更新每个对象的属性。
我的用例是我在一篇博客文章上有一堆评论,我想迭代一篇博客文章上的每一条评论,并将博客文章上的datetime设置为+10小时。我可以用SQL来做,但我想把它保留在业务层。
是否有一种方法来做以下使用LINQ?
foreach (var c in collection)
{
c.PropertyToSet = value;
}
为了澄清,我希望遍历集合中的每个对象,然后更新每个对象的属性。
我的用例是我在一篇博客文章上有一堆评论,我想迭代一篇博客文章上的每一条评论,并将博客文章上的datetime设置为+10小时。我可以用SQL来做,但我想把它保留在业务层。
当前回答
不,LINQ不支持大规模更新。唯一更短的方法是使用ForEach扩展方法-为什么IEnumerable上没有ForEach扩展方法?
其他回答
这是我使用的扩展方法…
/// <summary>
/// Executes an Update statement block on all elements in an IEnumerable of T
/// sequence.
/// </summary>
/// <typeparam name="TSource">The source element type.</typeparam>
/// <param name="source">The source sequence.</param>
/// <param name="action">The action method to execute for each element.</param>
/// <returns>The number of records affected.</returns>
public static int Update<TSource>(this IEnumerable<TSource> source, Func<TSource> action)
{
if (source == null) throw new ArgumentNullException("source");
if (action == null) throw new ArgumentNullException("action");
if (typeof (TSource).IsValueType)
throw new NotSupportedException("value type elements are not supported by update.");
var count = 0;
foreach (var element in source)
{
action(element);
count++;
}
return count;
}
实际上我找到了一个扩展方法,可以很好地完成我想要的
public static IEnumerable<T> ForEach<T>(
this IEnumerable<T> source,
Action<T> act)
{
foreach (T element in source) act(element);
return source;
}
我的2便士:-
collection.Count(v => (v.PropertyToUpdate = newValue) == null);
我正在做这个
Collection.All(c => { c.needsChange = value; return true; });
引用Adi Lester的回答(https://stackoverflow.com/a/5755487/8917485)
我很喜欢这个答案,但这个答案有一个错误。它只是改变一个新创建的列表中的值。它必须更改为两行才能读取真正的更改列表。
var aList = collection.ToList();
aList.ForEach(c => c.PropertyToSet = value);