Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update a single item of liist of objects using LINQ in C#

I want like to update the Value of the list which has property Text="ALL".

public class Season
    {
      public string Text {get;set;}
      public string Value {get;set;}
      public bool ValueSelected {get;set;}
    }
like image 861
Dangerous Dev Avatar asked Feb 06 '13 12:02

Dangerous Dev


1 Answers

The 'Q' in LINQ stands for "Query". LINQ is not meant to update objects.

You can use LINQ to find the object you want to update and then update it "traditionally".

var toUpdate = _seasons.Single(x => x.Text == "ALL");

toUpdate.ValueSelected = true;

This code assumes that there is exactly one entry with Text == "ALL". This code will throw an exception if there is none or if there are multiple.

If there is either none or one, use SingleOrDefault:

var toUpdate = _seasons.SingleOrDefault(x => x.Text == "ALL");

if(toUpdate != null)
    toUpdate.ValueSelected = true;

If it's possible that there are multiple, use Where:

var toUpdate = _seasons.Where(x => x.Text == "ALL");

foreach(var item in toUpdate)
    item.ValueSelected = true;
like image 54
Daniel Hilgarth Avatar answered Sep 28 '22 01:09

Daniel Hilgarth