如果匹配,则仅添加到列表

时间:2011-09-19 19:54:53

标签: c# string list compare

我有一个我要导入RTB的文件:

// Some Title
// Some Author
// Created on
// Created by
//

Format:
 "Text Length" : 500 lines
 "Page Length" : 20 pages

Component: 123456
 "Name" : Little Red Riding Hood
 "Body Length" : 13515 lines
 ........etc // can have any number of lines under 'Component: 123456'

Component: abcd
 "Name" : Some other Text
 "Body Length" : 12 lines
 ........etc // can have any number of lines under 'Component: abcd'


... etc, etc  // This can occur thousands of times as this file has an unset length.

现在发生的事情是从 Component: 123456 存储的值,直到它到达下一个Component (恰好是abcd进入List<string>位置0.下一个将位于位置1 ..依此类推,直到读完整个文件。

使用下面的代码,我可以解决上述问题:

string[] splitDataBaseLines = dataBase2FileRTB.Text.Split('\n');
StringBuilder builder = null;
var components = new List<string>();
foreach (var line in splitDataBaseLines)
{
    if (line.StartsWith("Component : "))
    {
        if (builder != null)
        {
            components.Add(builder.ToString());
            builder = new StringBuilder();
        }
        builder = new StringBuilder();
    }
    if (builder != null)
    {
        builder.Append(line);
        builder.Append("\r\n");
    }
}
if (builder != null)
    components.Add(builder.ToString());

但是,现在这项工作正常我需要操作此代码,只有在不同的匹配时才将其添加到 components列表 >列表。

为了找出该行是否匹配,我可以将其添加到components列表中,我需要拆分上面的起始行。我这样做是通过添加以下代码:

string partNumberMatch;

if (line.StartsWith("Component : "))
{
    partNumberMatch = line.Split(':');
    if (builder != null)
    {
    //....
}

现在我有了组件编号/字符串,我需要将它与另一个列表进行比较......我正在考虑做类似的事情:

foreach (var item in theOtherList) 
{
    if (item.PartNumber.ToUpper().Equals(partNumberMatch[1]))
}

但我不认为这是最好的方式,或者这种方式是否真的有效..

所以我的问题是,有人可以帮我比较这两个字符串,看看它们是否匹配,如果项目匹配,只将组件值添加到component列表。

特别感谢Jon Skeet

1 个答案:

答案 0 :(得分:0)

这就是我想出来让它发挥作用的地方:

StreamWriter sw2 = new StreamWriter(saveFile2.FileName);
Boolean partMatch = false;
Boolean isAMatch = false;
List<string> newLines = new List<string>();
string[] splitDataBaseLines = dataBase2FileRTB.Text.Split('\n');

foreach (var item in theOtherList)
{
    foreach (var line in splitDataBaseLines)
    {
        if (line.StartsWith("Component : "))
        {
            partNumberMatch = line.Split(':');
            partNumberMatch[1] = partNumberMatch[1].Remove(0,2);
            partNumberMatch[1] = partNumberMatch[1].TrimEnd('"');

            if (partNumberMatch[1].Equals(item.PartNumber))
            {
                isAMatch = true;
                sw2.WriteLine();
            }

            partMatch = true;
        }

        if (line.Equals(""))
        {
            partMatch = false;
            isAMatch = false;
        }

        if (partMatch == true && isAMatch == true)
            sw2.WriteLine(line);
    }
}
sw2.Close();
相关问题