Home > front end >  Convert Linq operation syntax to query syntax
Convert Linq operation syntax to query syntax

Time:12-29

I'm trying to figure out how to convert this method syntax into query syntax:

result.Select(c => { c.property1 = 100; return c; }).ToList();

CodePudding user response:

If you are working with record or struct types, you can use the with expression to modify an object within a linq expression.

Note that this will make copies of the objects and not modify the original objects. Given the code in your question, the original objects are being modified if they are of reference type.

public struct Demo
{
    public int Property1 { get; set; }
}

List<Demo> list = new List<Demo>();

var modifiedList = from d in list
                   select d with {Property1 = 100};

If you want to modify the objects in the list and the objects in the list are of reference type and you are just looking for a concise way of writing the code, use ForEach instead of Select:

public class Demo
{
    public int Property1 { get; set; }
}

List<Demo> list = new List<Demo>();

list.ForEach(d => d.Property1 = 100);

Note that this will NOT work for value types like struct because in that case you would work on copies.

It will also not be a lot more or less efficient than using a traditional foreach loop:

foreach(var d in list) { d.Property1 = 100; }

CodePudding user response:

What about this?

(from c in result
 select { c.property1 = 100; return c; })
.ToList();

Or

(from c in result
 select new { c.property1 = 100, c })
.ToList();
  • Related