FloatLeft
FloatLeft

Reputation: 1337

Query and updating a property in a collection using LINQ

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");

Upvotes: 20

Views: 33628

Answers (3)

Atul Chaudhary
Atul Chaudhary

Reputation: 1133

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; });

Upvotes: 8

Stuart
Stuart

Reputation: 66882

You can change the order, then use the ForEach operator:

tickets
   .Where(x => x.Name == "Beach")
   .ToList()
   .ForEach(x => { x.Selected = true; });

Note:

  • that the ToList() is needed because IEnumerable doesn't support ForEach in Linq - see LINQ equivalent of foreach for IEnumerable<T>
  • that for readability it might be better to separate this out into a linq query and then a more conventional foreach(x in list) C# loop
  • if this is linq-to-sql, then you'll need to call SubmitChanges() in order to persist your changes.

Upvotes: 32

Jeff Mercado
Jeff Mercado

Reputation: 134811

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();

Upvotes: 1

Related Questions