有没有办法做到这一点,分配名单,其中内的值; T> .ForEach()语句? [英] Is there any way to do this, assign a value within a List<T>.ForEach() statement?

查看:103
本文介绍了有没有办法做到这一点,分配名单,其中内的值; T> .ForEach()语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的:

  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为字符串这里)

如果拉姆达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

这篇关于有没有办法做到这一点,分配名单,其中内的值; T&GT; .ForEach()语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆