C# linq assign new value to field
In C# LINQ, you can assign a new value to a field using the Select
method. Here are a few examples:
Example 1: Assign a new value to a field
var data = new[] { new { Id = 1, Name = "John" }, new { Id = 2, Name = "Jane" } };
var result = data.Select(x => new { x.Id, Name = "New Name" });
foreach (var item in result)
{
Console.WriteLine($"Id: {item.Id}, Name: {item.Name}");
}
In this example, we're selecting a new anonymous object with the same Id
field as the original object, but with a new value for the Name
field.
Example 2: Assign a new value to a field using a lambda expression
var data = new[] { new { Id = 1, Name = "John" }, new { Id = 2, Name = "Jane" } };
var result = data.Select(x => new { Id = x.Id, Name = x.Name == "John"? "New Name" : x.Name });
foreach (var item in result)
{
Console.WriteLine($"Id: {item.Id}, Name: {item.Name}");
}
In this example, we're using a lambda expression to assign a new value to the Name
field. If the original Name
field is "John", we assign "New Name", otherwise we keep the original value.
Example 3: Assign a new value to a field using a custom method
public static string GetNewName(string name)
{
return name == "John"? "New Name" : name;
}
var data = new[] { new { Id = 1, Name = "John" }, new { Id = 2, Name = "Jane" } };
var result = data.Select(x => new { Id = x.Id, Name = GetNewName(x.Name) });
foreach (var item in result)
{
Console.WriteLine($"Id: {item.Id}, Name: {item.Name}");
}
In this example, we're using a custom method GetNewName
to assign a new value to the Name
field. If the original Name
field is "John", we assign "New Name", otherwise we keep the original value.
Note that in all examples, we're creating a new anonymous object with the same fields as the original object, but with the new value assigned to the Name
field.