What is the most succint/simple way of updating a single property of a specific item within a collection using LINQ?
For example if I have a List of the following:
public class Ticket
{
public string Name { get; set; }
public string Code { get; set; }
public bool Selected { get; set; }
}
How can I use LINQ to update the "Selected" property of a Ticket item wheres its "Name" property has the value of "Beach". In SQL it would be:
UPDATE Tickets SET Selected = true WHERE Name = 'Beach'
I thought I was on the right track with this...
tickets.Select(x => { x.Selected = true; return x; }).ToList().Where(x => x.Name == "Beach");
You can update rows in a database by modifying member values of the objects associated with the LINQ to SQL Table<TEntity> collection and then submitting the changes to the database. LINQ to SQL translates your changes into the appropriate SQL UPDATE commands.
This query returns two groups based on the first letter of the word. List<int> numbers = new() { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; // The query variables can also be implicitly typed by using var // Query #1. IEnumerable<int> filteringQuery = from num in numbers where num < 3 || num > 7 select num; // Query #2.
While the LINQ methods always return a new collection, they don't create a new set of objects: Both the input collection (customers, in my example) and the output collection (validCustomers, in my previous example) are just sets of pointers to the same objects.
You can change the order, then use the ForEach operator:
tickets
.Where(x => x.Name == "Beach")
.ToList()
.ForEach(x => { x.Selected = true; });
Note:
ToList()
is needed because IEnumerable doesn't support ForEach in Linq - see LINQ equivalent of foreach for IEnumerable<T>
foreach(x in list)
C# loop SubmitChanges()
in order to persist your changes.Bit late for an answer but i think we don't have to convert to ToList()
as Mentioned by stuart what actually we can do is just tweak Stuart code(which is great piece of code) as following
tickets
.Where(x => x.Name == "Beach")
.All(x => x.Selected = true);
Another option
tickets
.Where(x => x.Name == "Beach")
.All(x => { x.Selected = true; return true; });
Let me start off by saying this, don't use LINQ to set properties like that, that's not how LINQ's meant to be used.
You should write the query to select the rows to be changed, change them in a loop, and submit the changes to the database (if LINQ to SQL).
var query = tickets.Where(ticket => ticket.Name == "Beach");
foreach (var item in query)
item.Selected = true;
// if LINQ to SQL
context.SubmitChanges();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With