score:961
while you can use a foreach
extension method, if you want to use just the framework you can do
collection.select(c => {c.propertytoset = value; return c;}).tolist();
the tolist
is needed in order to evaluate the select immediately due to lazy evaluation.
score:-4
suppose we have data like below,
var items = new list<string>({"123", "456", "789"});
// like 123 value get updated to 123abc ..
and if we want to modify the list and replace the existing values of the list to modified values, then first create a new empty list, then loop through data list by invoking modifying method on each list item,
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;
score:-1
quoting adi lester's answer (https://stackoverflow.com/a/5755487/8917485)
i quite like this answer, but this answer has a bug. it just changes values in a new created list. it must be changed to two lines to read the real changed list.
var alist = collection.tolist();
alist.foreach(c => c.propertytoset = value);
score:0
i assume you want to change values inside a query so you could write a function for it
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; }
}
but not shure if this is what you mean.
score:1
you can use magiq, a batch operation framework for linq.
score:1
here is the extension method i use...
/// <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;
}
score:1
some people consider this is a comment, but for me is an answer, because the right way to do something wrong is not do it. so, the answer for this question is in the question itself.
do not use linq to modify data. use a loop.
score:2
my 2 pennies:-
collection.count(v => (v.propertytoupdate = newvalue) == null);
score:2
you can use linq to convert your collection to an array and then invoke array.foreach():
array.foreach(mycollection.toarray(), item=>item.dosomestuff());
obviously this will not work with collections of structs or inbuilt types like integers or strings.
score:2
i wrote some extension methods to help me out with that.
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;
}
}
}
i am using it like this:
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
for reference the argument check:
/// <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");
}
}
}
}
score:5
no, linq doesn't support a manner of mass updating. the only shorter way would be to use a foreach
extension method - why there is no foreach extension method on ienumerable?
score:7
i've tried a few variations on this, and i keep going back to this guy's solution.
http://www.hookedonlinq.com/updateoperator.ashx
again, this is somebody else's solution. but i've compiled the code into a small library, and use it fairly regularly.
i'm going to paste his code here, for the off chance that his site(blog) ceases to exist at some point in the future. (there's nothing worse than seeing a post that says "here is the exact answer you need", click, and dead 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; } );
score:10
there is no built-in extension method to do this. although defining one is fairly straight forward. at the bottom of the post is a method i defined called iterate. it can be used like so
collection.iterate(c => { c.propertytoset = value;} );
iterate source
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++;
}
}
score:18
although you specifically asked for a linq solution and this question is quite old i post a non-linq-solution. this is because linq (=
language integrated query) is meant to be used for queries on collections. all linq-methods don’t modify the underlying collection, they just return a new one (or more precise an iterator to a new collection). thus whatever you do e.g. with a select
doesn’t effect the underlying collection, you simply get a new one.
of course you could do it with a foreach
(which isn't linq, by the way, but an extension on list<t>
). but this literally uses foreach
anyway, but with a lambda-expression. apart from this every linq method internally iterates your collection e.g. by using foreach
or for
, however it simply hides it from the client. i don’t consider this any more readable nor maintainable (think of edit your code while debugging a method containing lambda-expressions).
having said this shouldn't use linq to modify items in your collection. a better way is the solution you already provided in your question. with a classic loop you can easily iterate your collection and update its items. in fact all those solutions relying on list.foreach
are nothing different, but far harder to read from my perspective.
so you shouldn't use linq in those cases where you want to update the elements of your collection.
score:26
use:
listofstuff.where(w => w.thing == value).tolist().foreach(f => f.otherthing = vaulefornewotherthing);
i am not sure if this is overusing linq or not, but it has worked for me when wanting to update a specific items in the list for a specific condition.
score:29
i actually found an extension method that will do what i want nicely
public static ienumerable<t> foreach<t>(
this ienumerable<t> source,
action<t> act)
{
foreach (t element in source) act(element);
return source;
}
score:83
i am doing this
collection.all(c => { c.needschange = value; return true; });
score:421
collection.tolist().foreach(c => c.propertytoset = value);
Source: stackoverflow.com
Related Query
- Update all objects in a collection using LINQ
- Update all objects except one in a collection using Linq
- Best way to assign a value to a property of all objects in a collection using LINQ
- Possible to update a member for all objects in a collection using LINQ?
- Using LINQ to Objects to find items in one collection that do not match another
- Simple way to update IEnumerable objects using LINQ
- Sort a list and all its nested objects using LINQ
- Using LINQ to find all keys from one collection that are not in another?
- How to update a single item of liist of objects using LINQ in C#
- Finding objects which contains at least all elements from subset using RavenDB and LINQ
- How to separate all consecutive Objects using Linq (C#)
- Update all properties in list using linq
- Using LINQ I have a list of lists, how do I select all objects that exist in every list?
- Get all objects from a tree with a particular property using Linq
- Update one object in collection using LINQ
- How to get the second repeated item from a collection of objects using LINQ to object
- select and update based on a child objects property minimum value using Linq
- Loop and update object value in a collection using LINQ
- How to determine if all objects inside List<T> has the same property value using Linq
- Update One List of Objects Attribute with Other List using LINQ
- Remove all entries from collection, which are found in different collection using linq
- Using Linq to select x amount of objects from an observable collection
- How to fill properties of objects using LINQ and return collection
- Update List of objects based on matching type in Dictionary and another List using C# collection
- How to update my model code using LINQ
- Select all fields from collection with related items in another collection using LINQ
- Update list of objects using LINQ
- Best way to obtain objects from a collection that can be cast to a specific type using Linq
- How to update anonymous objects property using LINQ and Contains
- Using Linq to do: Compile a list of all lists within a list of objects
More Query from same tag
- Property binding to web controls in asp.net with linq and reflection
- How to group by IEnumerable property value
- Populating a List(Of String) from a Datatable using LINQ in VB.NET
- C# Dictionary elementSelector struggles with implicit IEnumerable cast
- CSV file to class via Linq
- How to include two object inside the same select on Linq MVC5
- How to filter child entity with Linq?
- How to extend the DBContext (of EF6.0) with custom security
- LINQ - .Any for class type list<string> and class type string
- Still get repeated strings when using 'Distinct()'
- LINQ Selecting Specific Data from 2 different XML Descendant
- How to use Group by of two elements in an object and get the count in List?
- Linq to XML - parse a node into dictionary
- Refining an Entity Framework result set using LINQ
- C# lambda inner join with max
- EF Model Query SELECT WHERE NOT IN
- Entity Framework - System.IndexOutOfRangeException
- Bundle .NET 3.5 libs with app, so it runs on machines with only .NET 2.0 installed?
- Is there any compact and elegant way in C# to simultaneously iterate through two lists?
- Changing a piece of code into expressions
- Lookup table dilemma
- LinqPad Not Returning Results With C# Statements
- Why Does LINQ Select Always Return One Row
- entity framework - inner join to left join
- How order of joins affect performance of a query
- What is the difference between LINQ query expressions and extension methods
- writing LINQ query to pivot the result
- LINQ Filter Implementation with Expressions
- Deserialize XML to List<>
- How to query a Datatable using LINQ and add values to a List?