Обновление всех объектов в коллекции с помощью LINQ
есть ли способ сделать следующее С помощью LINQ?
foreach (var c in collection)
{
c.PropertyToSet = value;
}
чтобы уточнить, я хочу перебрать каждый объект в коллекции, а затем обновить свойство для каждого объекта.
мой вариант использования - у меня есть куча комментариев к сообщению в блоге, и я хочу перебрать каждый комментарий к сообщению в блоге и установить datetime на сообщении в блоге на +10 часов. Я мог бы сделать это в SQL, но я хочу сохранить его на бизнес-уровне.
15 ответов
в то время как вы можете использовать ForEach
метод расширения, если вы хотите использовать только каркас вы можете сделать
collection.Select(c => {c.PropertyToSet = value; return c;}).ToList();
на ToList
необходимо для того, чтобы оценить выбор немедленно из-за ленивый оценке.
Я на самом деле найден метод расширения это сделает то, что я хочу красиво
public static IEnumerable<T> ForEach<T>(
this IEnumerable<T> source,
Action<T> act)
{
foreach (T element in source) act(element);
return source;
}
использование:
ListOfStuff.Where(w => w.Thing == value).ToList().ForEach(f => f.OtherThing = vauleForNewOtherThing);
Я не уверен, что это чрезмерное использование LINQ или нет, но это сработало для меня, когда я хотел обновить определенные элементы в списке для определенного условия.
для этого нет встроенного метода расширения. Хотя определение одно довольно прямолинейно. В нижней части сообщения находится метод, который я определил, называемый Iterate. Его можно использовать так
collection.Iterate(c => { c.PropertyToSet = value;} );
Перебирать Источник
public static void Iterate<T>(this IEnumerable<T> enumerable, Action<T> callback)
{
if (enumerable == null)
{
throw new ArgumentNullException("enumerable");
}
IterateHelper(enumerable, (x, i) => callback(x));
}
public static void Iterate<T>(this IEnumerable<T> enumerable, Action<T,int> callback)
{
if (enumerable == null)
{
throw new ArgumentNullException("enumerable");
}
IterateHelper(enumerable, callback);
}
private static void IterateHelper<T>(this IEnumerable<T> enumerable, Action<T,int> callback)
{
int count = 0;
foreach (var cur in enumerable)
{
callback(cur, count);
count++;
}
}
Я пробовал несколько вариантов этого, и я продолжаю возвращаться к решению этого парня.
http://www.hookedonlinq.com/UpdateOperator.ashx
опять же, это чье-то другое решение. Но я скомпилировал код в небольшую библиотеку и использую его довольно регулярно.
Я собираюсь вставить его код здесь, на случай, если его сайт (блог) перестанет существовать в какой-то момент в будущем. (Нет ничего хуже, чем видеть сообщение, в котором говорится "Вот точный ответ, который вам нужен", нажмите и мертвый URL.)
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 не поддерживает способ массового обновления. Единственное короче способ использования ForEach
метод расширения - Почему нет метода расширения ForEach на IEnumerable?
Я написал некоторые методы расширения, чтобы помочь мне с этим.
namespace System.Linq
{
/// <summary>
/// Class to hold extension methods to Linq.
/// </summary>
public static class LinqExtensions
{
/// <summary>
/// Changes all elements of IEnumerable by the change function
/// </summary>
/// <param name="enumerable">The enumerable where you want to change stuff</param>
/// <param name="change">The way you want to change the stuff</param>
/// <returns>An IEnumerable with all changes applied</returns>
public static IEnumerable<T> Change<T>(this IEnumerable<T> enumerable, Func<T, T> change )
{
ArgumentCheck.IsNullorWhiteSpace(enumerable, "enumerable");
ArgumentCheck.IsNullorWhiteSpace(change, "change");
foreach (var item in enumerable)
{
yield return change(item);
}
}
/// <summary>
/// Changes all elements of IEnumerable by the change function, that fullfill the where function
/// </summary>
/// <param name="enumerable">The enumerable where you want to change stuff</param>
/// <param name="change">The way you want to change the stuff</param>
/// <param name="where">The function to check where changes should be made</param>
/// <returns>
/// An IEnumerable with all changes applied
/// </returns>
public static IEnumerable<T> ChangeWhere<T>(this IEnumerable<T> enumerable,
Func<T, T> change,
Func<T, bool> @where)
{
ArgumentCheck.IsNullorWhiteSpace(enumerable, "enumerable");
ArgumentCheck.IsNullorWhiteSpace(change, "change");
ArgumentCheck.IsNullorWhiteSpace(@where, "where");
foreach (var item in enumerable)
{
if (@where(item))
{
yield return change(item);
}
else
{
yield return item;
}
}
}
/// <summary>
/// Changes all elements of IEnumerable by the change function that do not fullfill the except function
/// </summary>
/// <param name="enumerable">The enumerable where you want to change stuff</param>
/// <param name="change">The way you want to change the stuff</param>
/// <param name="where">The function to check where changes should not be made</param>
/// <returns>
/// An IEnumerable with all changes applied
/// </returns>
public static IEnumerable<T> ChangeExcept<T>(this IEnumerable<T> enumerable,
Func<T, T> change,
Func<T, bool> @where)
{
ArgumentCheck.IsNullorWhiteSpace(enumerable, "enumerable");
ArgumentCheck.IsNullorWhiteSpace(change, "change");
ArgumentCheck.IsNullorWhiteSpace(@where, "where");
foreach (var item in enumerable)
{
if (!@where(item))
{
yield return change(item);
}
else
{
yield return item;
}
}
}
/// <summary>
/// Update all elements of IEnumerable by the update function (only works with reference types)
/// </summary>
/// <param name="enumerable">The enumerable where you want to change stuff</param>
/// <param name="update">The way you want to change the stuff</param>
/// <returns>
/// The same enumerable you passed in
/// </returns>
public static IEnumerable<T> Update<T>(this IEnumerable<T> enumerable,
Action<T> update) where T : class
{
ArgumentCheck.IsNullorWhiteSpace(enumerable, "enumerable");
ArgumentCheck.IsNullorWhiteSpace(update, "update");
foreach (var item in enumerable)
{
update(item);
}
return enumerable;
}
/// <summary>
/// Update all elements of IEnumerable by the update function (only works with reference types)
/// where the where function returns true
/// </summary>
/// <param name="enumerable">The enumerable where you want to change stuff</param>
/// <param name="update">The way you want to change the stuff</param>
/// <param name="where">The function to check where updates should be made</param>
/// <returns>
/// The same enumerable you passed in
/// </returns>
public static IEnumerable<T> UpdateWhere<T>(this IEnumerable<T> enumerable,
Action<T> update, Func<T, bool> where) where T : class
{
ArgumentCheck.IsNullorWhiteSpace(enumerable, "enumerable");
ArgumentCheck.IsNullorWhiteSpace(update, "update");
foreach (var item in enumerable)
{
if (where(item))
{
update(item);
}
}
return enumerable;
}
/// <summary>
/// Update all elements of IEnumerable by the update function (only works with reference types)
/// Except the elements from the where function
/// </summary>
/// <param name="enumerable">The enumerable where you want to change stuff</param>
/// <param name="update">The way you want to change the stuff</param>
/// <param name="where">The function to check where changes should not be made</param>
/// <returns>
/// The same enumerable you passed in
/// </returns>
public static IEnumerable<T> UpdateExcept<T>(this IEnumerable<T> enumerable,
Action<T> update, Func<T, bool> where) where T : class
{
ArgumentCheck.IsNullorWhiteSpace(enumerable, "enumerable");
ArgumentCheck.IsNullorWhiteSpace(update, "update");
foreach (var item in enumerable)
{
if (!where(item))
{
update(item);
}
}
return enumerable;
}
}
}
Я использую его так:
List<int> exampleList = new List<int>()
{
1, 2 , 3
};
//2 , 3 , 4
var updated1 = exampleList.Change(x => x + 1);
//10, 2, 3
var updated2 = exampleList
.ChangeWhere( changeItem => changeItem * 10, // change you want to make
conditionItem => conditionItem < 2); // where you want to make the change
//1, 0, 0
var updated3 = exampleList
.ChangeExcept(changeItem => 0, //Change elements to 0
conditionItem => conditionItem == 1); //everywhere but where element is 1
Для справки проверка аргумента:
/// <summary>
/// Class for doing argument checks
/// </summary>
public static class ArgumentCheck
{
/// <summary>
/// Checks if a value is string or any other object if it is string
/// it checks for nullorwhitespace otherwhise it checks for null only
/// </summary>
/// <typeparam name="T">Type of the item you want to check</typeparam>
/// <param name="item">The item you want to check</param>
/// <param name="nameOfTheArgument">Name of the argument</param>
public static void IsNullorWhiteSpace<T>(T item, string nameOfTheArgument = "")
{
Type type = typeof(T);
if (type == typeof(string) ||
type == typeof(String))
{
if (string.IsNullOrWhiteSpace(item as string))
{
throw new ArgumentException(nameOfTheArgument + " is null or Whitespace");
}
}
else
{
if (item == null)
{
throw new ArgumentException(nameOfTheArgument + " is null");
}
}
}
}
вот метод расширения, который я использую...
/// <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;
}
хотя вы специально попросили linq-решение, и этот вопрос довольно старый, я публикую не-linq-решение. Это потому, что linq (=lanuguage интегрирован запрос) используется для запросов к коллекциям. Все linq-методы не изменяют базовую коллекцию, они просто возвращение новый (или, точнее, итератор для новой коллекции). Таким образом, что бы вы ни делали, например, с Select
не влияет на базовую коллекцию, вы просто получаете новый один.
конечно мог бы у него с ForEach
(кстати, это не linq, а расширение на List<T>
). Но это!--10-->буквально использует foreach
в любом случае, но с лямбда-выражением. Кроме этого каждый linq-метод внутренне повторяет вашу коллекцию, например, используя foreach
или for
, однако он просто скрывает его от клиента. Я не считаю это более читаемым и поддерживаемым (подумайте об изменении кода во время отладки метод, содержащий лямбда-выражения).
сказав это, следует использовать Linq to изменить элементов в вашей коллекции. Лучшим способом является решение, которое вы уже предоставили в своем вопросе. С помощью классического цикла вы можете легко перебирать свою коллекцию и обновлять ее элементы. На самом деле все эти решения полагаются на List.ForEach
ничего другого, но гораздо труднее читать с моей точки зрения.
поэтому вы не должны использовать linq в тех случаях, когда вы хотите обновление элементы вашей коллекции.
Я предполагаю, что вы хотите изменить значения внутри запроса, чтобы вы могли написать для него функцию
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 для преобразования вашей коллекции в массив, а затем вызвать массива.По каждому элементу():
Array.ForEach(MyCollection.ToArray(), item=>item.DoSomeStuff());
очевидно, что это не будет работать с коллекциями структур или встроенных типов, таких как целые числа или строки.