Is there any way to do this, assign a value within a List.ForEach() statement?

后端 未结 4 714
臣服心动
臣服心动 2021-01-22 22:08

I have this:

var lineArray = line.Split(\';\');

lineArray.ToList().ForEach(x =>
{
    if (x == \"(null)\")
        x = \"NULL\";
    else
        x = string.         


        
4条回答
  •  猫巷女王i
    2021-01-22 23:03

    var lineArray = line.Split(';')
                        .Select(x=>x == "(null)"
                                   ? "NULL"
                                   : string.Format("'{0}'", x))
                        .ToArray();
    

    you are trying to use List.ForEach(Action action) with lambda expression (T is string here)

    if lambda expression is replaced with named method it turns out that only method argument is modified, but changes are not reflected on calling side, because x is not ref argument

    private void Replace(string x)
    {
        if (x == "(null)")
            x = "NULL";
        else
            x = string.Format("'{0}'", x);
    }
    
    var list = lineArray.ToList();
    list.ForEach(Replace);
    // check list here and make sure that there are no changes
    

    ForEach could work if T is a reference type and action modifies some properties but not the reference itself

提交回复
热议问题