1
IList<Item> items = new List<Item>();
items.Add(new Item
{
     tag = "{" + Ann + "}",
     value = "Anny"
});

items.Add(new Item
{
     tag = "{" + John + "}",
     value = "Johnny"
});

How can I use Linq to select tag with {John} and replace value with "Jane"?

Alvin
  • 8,219
  • 25
  • 96
  • 177
  • 2
    Since `items` is a list and the value you're searching for can appear at any position you have to examine every element. This can only be solved by using some looping construct. Why do you want to be able to do this without a loop, and what makes you think such a solution would be possible? – Yuck Mar 16 '17 at 03:26

2 Answers2

0

LINQ is, as the name suggests, more of a query tools. So you can get specific item(s) that you want to modify from a collection using LINQ, but the modification itself is out-of-scope for LINQ.

Assuming that there is always maximum one match to your criteria, you can do as follows :

var john = items.FirstOrDefault(o => o.tag == "{John}");
if(john != null)
{
    john.value = "Jane";
}

Otherwise, you can use LINQ Where(o => o.tag == "{John}") to get the target items for modification. But then you'll need to iterate through the result to actually update the value of each matched item.

har07
  • 88,338
  • 12
  • 84
  • 137
  • This is still looping. In the best case your match is found in the first position and stops. In the worst case your match is found at the last position, in which case you've looped over the entire list. LINQ does not magically avoid looping. It simply provides a compact way of doing so. – Yuck Mar 16 '17 at 11:04
  • @Yuck Agreed. Only I assumed, by looping, OP means a traditional looping construct i.e `foreach`, `for`, `while`, etc, – har07 Mar 17 '17 at 01:15
0
items.Where(o => o.tag == "{"+John+"}").ToList().ForEach(item =>{
        item.value = "Jane";
        });

Here is working fiddle

jitender
  • 10,238
  • 1
  • 18
  • 44
  • This is still looping. – Yuck Mar 16 '17 at 11:02
  • @Yuck yes it's looping but looping on the items those match the tag name not all items. http://stackoverflow.com/a/2433386/5621827 – jitender Mar 16 '17 at 11:56
  • How do you think `Where` is able to determine which elements qualify? It has to loop over the list to find the matches. Then it has to call `ForEach`. You're also calling `ToList` which will make a copy of the list (though not the elements referenced by that list). – Yuck Mar 16 '17 at 15:23
  • @Yuck I got your point thanks.I am just wondering if there is some other solution in this case – jitender Mar 17 '17 at 04:42