Wilz
Wilz

Reputation: 239

C# LINQ to objects query to change the field value based on List

I have the follwing objects

 objItem (id,name,qty)  - list<items>
 objSel(selId)      - list<int>

objSel.selId is the selected item id of objItem.

How to write the LINQ query to change item qty to 0 if the items are not selected and return objItem.

Upvotes: 0

Views: 972

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1502835

Your pseudo-code is quite confusing, but I suspect you want something like:

List<Item> items = ...;
List<int> selectedIds = ...;

foreach (var item in items.Where(x => !selectedIds.Contains(x.Id)))
{
    item.Quantity = 0; // Property name adjusted for readability and convention
}

For more efficiently, use HashSet<int> for the selected IDs instead.

Note that it's not the LINQ query which performs the change - the query just gives the items which require changing. While you can abuse LINQ to change data, it's a bad idea to do so. The clue is in the word "query" - it's about asking a question. What you do with the answer to that question is a different matter.

Upvotes: 1

Related Questions