有没有办法做到这一点,分配名单,其中内的值; T> .ForEach()语句?这一点、没有办法、语句、分配

2023-09-07 03:01:08 作者:茶凉酒寒

我有这样的:

  VAR lineArray = line.Split(';');

。lineArray.ToList()的ForEach(X =>
{
    如果(X ==(空))
        X =空;
    其他
        X =的String.Format('{0}',X);
});
 

这个运行良好,但似乎并没有改变在 lineArray 的元素。我想起了的ForEach 的结果分配给一个 VAR ,但它返回void。

任何想法?

编辑:我想这是因为了ToList()返回值未分配的任何地方......

解决方案

  VAR lineArray = line.Split(';')
                    。选择(X = X的催化剂==(空)
                               ? 空值
                               :的String.Format('{0}',X))
                    .ToArray();
 

您要使用名单,其中,T> .ForEach(动作< T>动作)与拉姆达EX pression(T为字符串这里)

资深操盘手 换手率10 代表什么意思 不懂的股民请不要炒股

如果拉姆达EX pression被替换命名的方法事实证明,唯一的方法参数进行修改,但更改不会反映在调用方,因为 X 是没有 REF 参数

 私人无效替换(字符串x)
{
    如果(X ==(空))
        X =空;
    其他
        X =的String.Format('{0}',X);
}

VAR列表= lineArray.ToList();
list.ForEach(替换);
//检查列表在这里,并确保没有任何变化
 

的ForEach可以工作,如果T是引用类型和行为会修改某些属性,但不是引用本身

I have this:

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

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

This runs fine, but does not seem to change the elements within lineArray. I thought of assigning the results of ForEach to a var but it returns void.

Any ideas ?

EDIT: I think it's because ToList() return value is not assigned anywhere...

解决方案

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