tags:

views:

61

answers:

3

How do I do something like the following, assinging new values based on condition within a linq method but keeping all results.

 int x= 100;

 var results= from r in Results where r.id==id select r
              { if r.value==x set r.result="Found"}
+2  A: 

You're not really meant to - ideally queries shouldn't have side effects. I mean you can do:

var results = Results.Where(r => r.id == id)
                     .Select(r => { 
                          if (r.value == x)
                          {
                              r.result = "Found"; 
                          }
                          return r; 
                      };

I'd generally try not to though...

Note that this really won't work in LINQ to SQL etc.

Jon Skeet
would being 'side effect free' also include not creating a new object such as .Select(r=> new SomeObject(){id=r.id,name=r.name}) in the same method?
zsharp
@zsharp: That doesn't affect existing objects, so it's okay.
Jon Skeet
+1  A: 

Linq should not be used in that way. I would iterate over the results of the query and then change them.

 var results= from r in Results where r.id==id select r;

 foreach (var r in results.ToList()) { if (r.value==x) r.result="Found"; }
Botz3000
+2  A: 

It's probably better to make a second pass so you can keep your query clean and side-effect-free.

int x = 100;

List<Result> results = (from r in Results
                        where r.id == id
                        select r).ToList();

results.ForEach(r => r.result = r.value == x ? "Found" : "Not Found");
Jacob Proffitt