Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify elements in list with ForEach lambda

Tags:

c#

linq

I want to filter a string array:

string[] args

from the command line, e.g: "-command1 x y -command2 a b -command3 c d"

Taking all the words with a '-' at the beginning, then converting those to upper case.

var commands = args.Where(x => x.StartsWith("-")).ToList<String>();
commands.ForEach(x => {
    x.ToUpper()
    });
commands.ToString();

This will return the args list with words starting with '-' lower case - that is the lambda is not being applied. Why is this? Is a copy of the list being made for the lambda capture, and that is modified, not the origina list itself?

like image 383
friartuck Avatar asked Sep 04 '15 03:09

friartuck


1 Answers

var commands = args.Where(x => x.StartsWith("-")).Select(y => y.ToUpper()).ToList();

or

var upperCommands = new List<String>();
var commands = args.Where(x => x.StartsWith("-")).ToList<String>();
    commands.ForEach(x => upperCommands.Add(
        x.ToUpper());
like image 99
Sateesh Pagolu Avatar answered Oct 12 '22 22:10

Sateesh Pagolu