如何使用linq替换类型字符串列表中的某些特定字符串? [英] How to replace some particular string in a list of type string using linq?

查看:93
本文介绍了如何使用linq替换类型字符串列表中的某些特定字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我有一些类型的字符串列表.我想使用linq替换某些物品,我该怎么做?我下面的代码工作正常,但我想使用linq的功能在一行代码中完成此操作.

Hi all I have list of type string with some items. i want to replace some items using linq, how can i do that? my below code is working fine but i want to do this in single line of code using the power of linq.

这是我的代码:

List<string> listcolumns = columns.ToList();//Array to list

if (listcolumns.Contains("HowToReplace") && listcolumns.Contains("HowTo Replace"))
{
    int index = 0;
    index = listcolumns.IndexOf("HowToReplace");
    if (index > 0)
    {
        listcolumns.RemoveAt(index);
        listcolumns.Insert(index, "HowTo Replace");
    }
    index = listcolumns.IndexOf("HowToReplace");
    if (index > 0)
    {
        listcolumns.RemoveAt(index);
        listcolumns.Insert(index, "HowTo Replace");
    }
    columns = listcolumns.ToArray<string>();//List to array
}

推荐答案

使用Linq:

listColumns.Select<string,string>(s => s == "HowToReplace" ? "HowTo Replace" : s).ToArray();

没有Linq:

 for (int i=0; i<listColumns.Length; i++) 
    if (ListColumns[i] == "HowToreplace") ListColumns[i] ="HowTo Replace");

这篇关于如何使用linq替换类型字符串列表中的某些特定字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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