How to change a property during a LINQ query?

Asked

Viewed 743 times

3

Is there any way to change in the LINQ query a property of the query itself?

Ex.: I’m doing a consultation on a List<Cliente> and I want all customers whose NomeFantasia begin with * have the symbol removed from the name.

Here’s the consultation I’m doing. I thought I’d make a Select, putting all class fields in the query, but how I need to return a List<Cliente> that wouldn’t work.

var ret = this.FindAll().Where(x => x.Id > 10).OrderBy(x => x.NomeFantasia);
  • I don’t understand yet... You want to receive the data and then change it in the original collection or only in the result?

1 answer

6


It’s even possible but you need to understand that the idea of LINQ is the functional programming style that preaches immutability. And the name itself demonstrates this. Q is from query, of consultation, and not manipulation, updating.

So although it is possible using some confusing technique, it goes against the intention of the resource and it is better to use the traditional algorithm to do the manipulation. You can even use LINQ to determine all collection elements that meet the established condition and deserve manipulation and then manipulate into a foreach. Many will prefer to do the consultation and manipulation on within the foreach. In this case it is so simple that LINQ is disposable.

foreach (var item in clientes) item.NomeFantasia.Replace("*", "");

Or if you want to just start:

foreach (var item in clientes) item.NomeFantasia.TrimStart('*');

I don’t know if I fully understand your goal but it’s that simple. Even if you want to do something a little different, the basis is this. Of course, LINQ can still be used to make other filters. But if it is related it is probably best to put a if within the foreach even.

If you insist:

var resultado = clientes.Select(item => { item.NomeFantasia.TrimStart('*'); return item; })

I put in the Github for future reference.

But note that the update will not run at this time. It is characteristic of LINQ to have a delayed execution.

I found no LINQ shorter :)

  • My intention was to avoid the foreach, but it seems there’s no way at all.

  • As I said LINQ is not solution to everything.

  • Yeah, I get it. It’s just that if you stop to analyze it’s a very simple question...

  • The secret is that it is written, even a simple change, it is not ideal. So much so that it does not have a LINQ-compatible extension method called Write, Replace, Update, or something like that. They didn’t forget, they would be bad. by causing side effect.

  • A detail: AP wanted to remove '*' at the beginning. It removes all. If you use it, see if this is not a problem.

  • Okay, there’s both. This is just secondary detail of what’s most important in the question.

  • That’s just detail @Rsinohara

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.