0

I have a class Like this,

class Test
{
    public int ID { get; set; }
    public string Name { get; set; }
}

I want to select eligible items in List, I also want to set Name to null of the result list. I don't want to loop the collection again to set property value, is there a way to set the property value during the selection in linq?

This is my current query:

var v = from t in tests where ids.Contains(t.ID) select t;

Thanks

Allen4Tech
  • 2,094
  • 3
  • 26
  • 66
  • Looks that this topic can help http://stackoverflow.com/questions/807797/linq-select-an-object-and-change-some-properties-without-creating-a-new-object – Anatoliy Sep 29 '14 at 08:11

1 Answers1

3

You can set it to null explicitly:

var newTests = tests.Where(test => ids.Contains(test.ID))
                    .Select(test => { 
                                       test.Name = null; 
                                       return test;
                                    });

Or you can project new instances of Test:

var newTests = tests.Where(test => ids.Contains(test.ID))
                    .Select(test => new Test { ID = test.ID });
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321