c# - Using Where and ForEach to modify specific elements in a list -
if have list of objects have properties fruitname , numfruits , want pluralize fruitname numfruits greater 1, possible in single statement chaining where , foreach?
something like:
fruitlist.where(fl => fl.numfruits > 1).foreach(fl => fl.fruitname = fl.fruitname + "s"); i tried above , doesn't work. complains system.collections.generic.ienumerable doesn't contain definition foreach.
if want one-liner (it harder maintain) , want keep original list intact modify of elements, you'll have use full anonymous function. if need multiple statements (a block of code), you'll need include braces , statement-terminating semicolons below:
fruitlist.foreach(fl => { fl.fruitname = fl.numfruits > 1 ? fl.fruitname + "s" : fl.fruitname; }); this works on original list (no subset) , exact same thing structured foreach do.
Comments
Post a Comment