NoviceToDotNet
NoviceToDotNet

Reputation: 10805

How to change value of an object using linq

I have the following statment that if isdefault is true to this collection i need to set each object isDefault property to false.

  custHead.lstCustomziation.Where(x => x.IsDefaultSelected == true).Select(x=>{x.IsDefaultSelected=false});

lstCustomziation  is a collection.

Upvotes: 1

Views: 1010

Answers (4)

Lombas
Lombas

Reputation: 1132

Linq may have been initially created for querying but it has evolved and is used as functional programming methods, equivalents to "map", "reduce", and "filter" used in other languages.

In your example I would suggest:

var list = custHead.lstCustomziation.Where(x => x.IsDefaultSelected == true)
            .Select(x=> TransformItem(x));

private XType TransformItem(XType item){
    item.IsDefaultSelected=false;
    return item;
}

Upvotes: 0

D Stanley
D Stanley

Reputation: 152521

Linq is for querying, not updating. You can get a list of the items you want to change and then update using a normal loop:

var list = custHead.lstCustomziation.Where(x => x.IsDefaultSelected == true)

foreach(var item in list)
    item.IsDefaultSelected=false;

Upvotes: 5

ken2k
ken2k

Reputation: 48975

As the Q of LINQ says, LINQ is designed for queries, not updates.

Just enumerate the LINQ result and apply your update.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500065

LINQ is for querying. You should use a foreach loop to make changes:

foreach (var item in custHead.lstCustomziation.Where(x => x.IsDefaultSelected))
{
    item.IsDefaultSelected = false;
}

That said, if IsDefaultSelected is false for the other items anyway, it may be simpler just to unconditionally set it:

foreach (var item in custHead.lstCustomziation)
{
    item.IsDefaultSelected = false;
}

Upvotes: 12

Related Questions