0

I want to be able to assign data to a set of values at a go without using a loop. something like this.

transactions.Where(x => x.sender == agent.realId).AllRows.Amount = 625000;

without doing something like this

var trans = transactions.Where(x => x.sender == agent.realId);
foreach(var t in trans)
{ 
    t.Amount = 625000;
}

Thanks in advance

2
  • whats wrong with that? Commented Feb 18, 2019 at 0:04
  • What's the source of the data (i.e. where does transactions come from)? Commented Feb 18, 2019 at 0:07

2 Answers 2

3

You could write an extension method that would allow you to perform an action for each element in the IEnumerable:

public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
    foreach (T item in source) { action(item); }
}

Then use it like this:

transactions.Where(x => x.sender == agent.realId).ForEach(t => t.Amount = 625000);
Sign up to request clarification or add additional context in comments.

1 Comment

MoreLinq also has this extension.
0

Well the thing is you can't really do it without a loop. If your objective is to make it look more linq-y you can do something similar to this:

transactions
    .Where(x => x.sender == agent.realId)
    .ToList()
    .ForEach(x => x.Amount = 625000);

But I personally am not a huge fan of this.

First of all, it's still a loop even though it's in a form of a function.

Secondly, even though it does look more like linq, it's really not. Linq operators are all based on functional programming principles, which implies immutability. Here however you want to assign a new value to the Amount property which is a mutable operation and therefore going against functional approach.

In conclusion, my advice is to use linq operators when you're doing functional stuff and use loops when you're doing imperative stuff. Shortly - use loops for assignments.

1 Comment

and also, this actually has two loops, one for ToList, and the other for ForEach. also there is memory allocation because of ToList.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.