使用子字符串过滤字符串数组

时间:2021-03-08 22:45:58

标签: c# arrays linq

所以我在数组中有这些值:

1_642-name.xml
1_642-name2.xml
1_678-name.xml
1_678-name2.xml

我总是只希望数字最高的值出现在我的数组中。但我似乎无法弄清楚如何?

字符串由以下因素组成:

<块引用>

1 是一个静态数字 - 并且永远只有 1

<块引用>

642 或 _ 和 - 之间的数字是一个身份,并且总是可以变大

<块引用>

name.xml 始终相同

在这种情况下,我想按最大标识 (678) 进行过滤。

我尝试过这样的事情,但没有运气:

string[] filter = lines.FindAll(lines, x => x.Substring(3, 3));

结果:

1_678-name.xml
1_678-name2.xml

2 个答案:

答案 0 :(得分:2)

因为您的格式中的字符数很容易变化,所以这对于正则表达式来说是一项很好的工作。例如:

var input = "1_642-name2.xml";
var pattern = @"^\d+_(\d+)-.+$";
var match = Regex.Match(input, pattern);

match.Groups[1].Value; // "642" (as a string)

可以在here找到正则表达式字符串的解释。

我们可以使用它来提取数组中每个元素的各个部分。

首先要做的是找到最大值,如果我们有这种格式:

#_###-wordswords

然后我们需要 _- 之间的数字。

var list = new string[]
{
    "1_642-name.xml",
    "1_642-name2.xml",
    "1_678-name.xml",
    "1_678-name2.xml"
};

var pattern = new Regex(@"^\d+_(\d+)-.+$");
var maxValue = list.Max(x => int.Parse(pattern.Match(x).Groups[1].Value));

这将找到“678”作为最大值。现在我们只需要过滤列表以仅显示该格式槽中具有“678”的条目。

var matchingEntries = list
    .Where(x => pattern.Match(x).Groups[1].Value == maxValue.ToString());

foreach (var entry in matchingEntries)
{
    Console.WriteLine(entry);
}

Where 用您的最大值过滤列表。

此代码有很多低效之处。我正在正则表达式解析每个值两次,并计算每个元素上 maxValue 的等效字符串。我会将修复这些作为练习留给读者。

答案 1 :(得分:1)

为了替代正则表达式,您还可以简单地解析每一行,检查数字,如果它是我们迄今为止发现的最大的行,则将该行添加到列表中。每当发现更大的数字时清除列表,然后在最后返回列表。

一个好处是我们只遍历列表一次而不是两次:

public static List<string> GetHighestNumberedLines(List<string> input)
{
    if (input == null || !input.Any()) return input;

    var result = new List<string>();
    var highNum = int.MinValue;

    foreach (var line in input)
    {
        var parts = line.Split('_', '-');
        int number;

        // Making sure we atually have a number where we expect it
        if (parts.Length > 1 && int.TryParse(parts[1], out number))
        {
            // If this is the highest number we've found, update
            // our variable and reset the list to contain this line
            if (number > highNum)
            {
                highNum = number;
                result = new List<string> {line};
            }
            // If this matches our high number, add this line to our list
            else if (number == highNum)
            {
                result.Add(line);
            }
        }
    }

    return result;
}
相关问题