LINQ lambda表达式替换字符串中的多个字符? [英] LINQ lambda expression to replace multiple characters in a string?

查看:1581
本文介绍了LINQ lambda表达式替换字符串中的多个字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能写一个lambda表达式将通过对象数组遍历和替换X的所有出现,'Y',''和'的属性之一Z'?

Is it possible to write a lambda expression that will iterate through array of objects and replace all occurences of 'X', 'Y', ' ' and 'Z' in one of the properties?

例如:

return query.Select(x => { x.SomePropertyName= x.SomePropertyName.Trim().Replace(' ', "_"); return x; }).ToList();



由于某些原因,查询上面并没有代替单个字符,当我需要更换多个字符。

For some reason, a query above doesn't replace a single character, when I need to replace multiple characters.

感谢您

推荐答案

当我要更换一次一些字符,与一个单一的其他角色,我经常使用string.Split和的string.join的组合:

When I want to replace one of a number of characters with one single other character, I often use a combination of string.Split and string.Join:

char[] unwanted = new[] {'X', 'Y', 'Z'};
query = query.Select(x =>
{
    x.SomePropertyName = string.Join("_", x.SomePropertyName.Split(unwanted));
    return x;
});

这将取代'X','Y''Z''_'。您可以与您所选择的循环结构结合这一点。

This will replace any occurrence of 'X', 'Y' or 'Z' with '_'. You can combine this with the looping construct of your choice.

由于在评论中讨论的那样,使用选择不果然在这种情况下,增加任何价值。一个正常的的foreach 循环会做的工作,甚至会产生更紧凑的代码:

As discussed in the comments, using Select does not really add any value in this case. A normal foreach loop would do the job, and would even produce more compact code:

char[] unwanted = new[] {'X', 'Y', 'Z'};
foreach(var x in query)
{
    x.SomePropertyName = string.Join("_", x.SomePropertyName.Split(unwanted));
};

这篇关于LINQ lambda表达式替换字符串中的多个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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