简体   繁体   English

修剪列表最后一个元素的结尾

[英]Trimming the end of a last element of a List

I am trimming a chracter from the end of the last element of a List and even though it works I feel it is not the best way of doing this. 我正在从List的最后一个元素的末尾修剪一个字符,即使它起作用了,我仍认为这不是最好的方法。

for (int i = lstTopicsDisplay.Count - 1; i >= 0; i--)
{
    if (i == lstTopicsDisplay.Count-1)
    {
        string lastValue = lstTopicsDisplay[i].TrimEnd(';');
        lstTopicsDisplay[i] = lastValue;
    }
}

Is there a better way, such as using a Lambda expression to get the same result? 是否有更好的方法,例如使用Lambda表达式获得相同的结果?

 int lastPos = lstTopicsDisplay.Count - 1;
 lstTopicsDisplay[lastPos] = lstTopicsDisplay[lastPos].TrimEnd(';')
lstTopicsDisplay.Last().TrimEnd(';')

As you are just changing one item in the list, you don't need the loop. 由于您仅更改列表中的一项,因此不需要循环。

Just calculating the index for the item that you want to change, and using the rest of the code unchanged: 只需计算要更改的项目的索引,然后使用其余代码即可:

int i = lstTopicsDisplay.Count - 1;

string lastValue = lstTopicsDisplay[i].TrimEnd(';');
lstTopicsDisplay[i] = lastValue;

Or simply: 或者简单地:

lstTopicsDisplay[lstTopicsDisplay.Count - 1] = lstTopicsDisplay[lstTopicsDisplay.Count - 1].TrimEnd(';');

尝试这个:

string lastValue = lstTopicsDisplay.[lstTopicsDisplay.Count - 1].TrimEnd(';');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM