How to change a property during a LINQ query?

3

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

Ex: I'm doing a query on List<Cliente> and I want all clients whose NomeFantasia starts with * to have the symbol removed from the name.

Here is the query I'm doing. I thought of doing a Select , putting all the fields of the class in the query, but since I need to return a List<Cliente> this would not work.

var ret = this.FindAll().Where(x => x.Id > 10).OrderBy(x => x.NomeFantasia);
    
asked by anonymous 14.08.2015 / 14:48

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. The Q is query , query , not manipulation, update.

So while it may be possible to use some confusing technique, it goes against the intent of the feature and it is better to use the traditional algorithm to do the manipulation. You can even use LINQ to determine all elements of the collection that meet the established condition and merit manipulation and then manipulate it in foreach . Many will prefer to query and manipulate within foreach . In this case it is so simple that LINQ is disposable.

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

Or if you just want to start:

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

I do not know if I fully understood 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 will probably be best to put if within foreach itself.

If you want to insist:

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

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

    
14.08.2015 / 15:05