c#string.replace在foreach循环中 [英] c# string.replace in foreach loop

查看:97
本文介绍了c#string.replace在foreach循环中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

某种程度上,我似乎无法在C#的foreach循环中获得字符串替换.我的代码如下:

Somehow I can't seem to get string replacement within a foreach loop in C# to work. My code is as follows :

foreach (string s in names)
{
    s.Replace("pdf", "txt");
}

对于LINQ还是很陌生的,所以如果这听起来很业余,请原谅我;)

Am still quite new to LINQ so pardon me if this sounds amateurish ;)

推荐答案

您说您正在寻求LINQ解决方案...这很容易:

You say you're after a LINQ solution... that's easy:

var replacedNames = names.Select(x => x.Replace("pdf", "txt"));

我们不知道names的类型,但是如果要分配回给它,则可以使用ToArrayToList:

We don't know the type of names, but if you want to assign back to it you could potentially use ToArray or ToList:

// If names is a List<T>
names = names.Select(x => x.Replace("pdf", "txt")).ToList();
// If names is an array
names = names.Select(x => x.Replace("pdf", "txt")).ToArray();

您应该注意,虽然您发布的代码目前根本没有使用LINQ ...

You should be aware that the code that you've posted isn't using LINQ at all at the moment though...

这篇关于c#string.replace在foreach循环中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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