Home > Software design >  updating a list using linq C#
updating a list using linq C#

Time:02-25

I have list in which I want to update is active flag from all user like

userList:[
    {'name':'a', isActive:'Y'},
    {'name':'b', isActive:'N'},
    {'name':'c', isActive:'Y'},
    {'name':'d', isActive:'N'},
];

I want to change isActive from Y to N and from N to Y, my updated list will look like below

userList:[
    {'name':'a', isActive:'N'},
    {'name':'b', isActive:'Y'},
    {'name':'c', isActive:'N'},
    {'name':'d', isActive:'Y'},
];

how can I achieve this?

CodePudding user response:

LINQ stands for Language Integrated Query - it's a tool for query, not modifying data. LINQ queries are not supposed to have side effects, like "every time you run it it changes the data and gives a different answer". It's also a side effect to change other data not related to the data being queried..

If you want to permanently change the items in your list using a lamdba based approach, you can use ForEach on List - this is not a LINQ thing; it's a List thing:

myList.ForEach(item => item.isActive = (item.isActive == 'Y' ? 'N' : 'Y'));

..but this isn't significantly different to the code Matt Watson posted in the comment, using a normal foreach


If you want to calculate-every-time-from-the-data the inverse of the current active, that's fine to do with LINQ:

myList.Select(item => 
  new Item{ 
    name = item.name, 
    isActive = (item.isActive == 'Y' ? 'N' : 'Y')
  }
);

You can run this over and over and the output is stable; if the myList data hasn't changed then the output from this will be a list that has items that are flipped in their active status


Here's a LINQ query that has a side effect; it modifies the array every time it runs:

enter image description here

The first time, Select did a[idx] which e.g. bumped array index 0 up from 1 to 2, but the operation returns the value before the increment e.g. 1 (and the a[0] is now 2).. This means you see "the original array" i.e. 1, 2, 3, 4 reflected in the z1 result, but z2 is the bumped up once (and the a is full of numbers that have been bumped twice)

Don't do this; it will cause a lot of problems. (I deliberately didn't put the code in as text, to hinder copy-pasting of code we shouldn't write)

  • Related