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

后端 未结 4 691
臣服心动
臣服心动 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条回答
  • 2021-01-22 22:40

    you can construct a new list from your original one :

    var newList = lineArray.Select(x => x == "(null)" ? "NULL" : string.Format("'{0}'", x));
    
    0 讨论(0)
  • 2021-01-22 22:51

    don't use ForEach like that - use a for loop.

    for (int i = 0; i < lineArray.Length; i++)
    {
        if (lineArray[i] == "(null)")
            lineArray[i] = "NULL";
        else
            lineArray[i] = string.Format("'{0}'", lineArray[i]);
    }
    
    0 讨论(0)
  • 2021-01-22 23:02

    I think this small change will work

     var lineArray = line.Split(';').ToList();
    
            lineArray.ForEach(x =>
            {
                if (x == "(null)")
                    x = "NULL";
                else
                    x = string.Format("'{0}'", x);
            });
    

    Below is a working example

    string line = "a;b;null;c;";
    
    var lineArray = line.Split(';').ToList();
    
        lineArray.ForEach(x =>
        {
            if (x == "(null)")
                x = "NULL";
            else
                x = string.Format("'{0}'", x);
        });
    

    Result:enter image description here

    If you need just to remove (null) values from the list, you do not need to loop just use removeAll

        lineArray.RemoveAll(a=>a.Equals("(null)"));
    

    working example below

    enter image description here

    0 讨论(0)
  • 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<T>.ForEach(Action<T> 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

    0 讨论(0)
提交回复
热议问题