C# 删除不必要的括号,但只留下一个

问题描述

我有以下不同大小的字符串列表

[5].[1].[2].[3].[4].__class SetobjectModel
[5].[1].[4].__class SetobjectModel
[5].[1].[4].[3].[1].__class SetobjectModel

我需要删除所有其他括号,只保留第一个

[5].__class SetobjectModel

有人对我如何实现这一目标有任何建议吗?

解决方法

这里是使用字符串的 Split 特性和 Join 的完整示例。 您可以阅读有关 Split hereJoin here

的更多信息
// source list of string to modify
var source = new List<string>()
{
    "[5].[1].[2].[3].[4].__class SetObjectModel","[5].[1].[4].__class SetObjectModel","[5].[1].[4].[3].[1].__class SetObjectModel"
};

// convert each element of source into a result set
var results = source.Select(value =>
{
    // split by the period 
    var splitted = value.Split(new[] { "." },StringSplitOptions.None);

    // join the first and last element with a period to match the format you want
    return string.Join(".",new[] { splitted.First(),splitted.Last() });
}).ToList();

这是不使用 Linq 和其他 quick 1 liner 进行转换的第二部分,以防您不熟悉它们

List<string> result = new List<string>();

foreach (string value in source)
{
    // split by the period
    string[] splitted = value.Split(new[] { "." },StringSplitOptions.None);

    // will contain the elements to keep and join
    List<string> elements = new List<string>();

    // add first element of the split
    elements.Add(splitted[0]);

    // add the last element of the split
    elements.Add(splitted[splitted.Length - 1]);

    // join the elements together
    string join = string.Join(".",elements);

    // add the join to the result set
    result.Add(join);
}