删除字符串列表

本文关键字:列表 字符串 删除 | 更新日期: 2023-09-27 18:06:26

我有这样的代码:

List<string> lineList = new List<string>();
foreach (var line in theFinalList)
{
    if (line.PartDescription != "")
        lineList.Add(line.PartDescription + " " + line.PartNumber + "'n");
    else
        lineList.Add("N/A " + line.PartNumber + "'n");
    //
    //This is what I am trying to fix:
    if (lineList.Contains("FID") || lineList.Contains("EXCLUDE"))
        // REMOVE THE item in the lineList
}

我试图在foreach循环中遍历theFinalList,并将每一行添加到一个名为lineList的新列表中。一旦添加,我想从列表中删除任何包含文本"FID""EXCLUDE"的条目。

我在删除条目时遇到了麻烦,有人能帮我吗?

删除字符串列表

为什么要添加它们呢?

lineList = theFinalList.Select( line => 
{
    if (line.PartDescription != "")
        return line.PartDescription + " " + line.PartNumber + "'n";
    else
        return "N/A " + line.PartNumber + "'n";
})
.Where(x => !(x.Contains("FID") || x.Contains("EXCLUDE")))
.ToList();

下面的代码示例遍历lineList并删除包含FID或EXCLUDE的行。

for(int i = lineList.Count - 1; i >= 0; i--)
{
    if (lineList[i].Contains("FID") || lineList[i].Contains("EXCLUDE"))
       lineList.RemoveAt(i);
}

在删除项时,以反向顺序遍历列表是很重要的。

当你在foreach循环中迭代theFinalList时,你不能删除theFinalList列表中的项目。在这种情况下,您可能会获得System.InvalidOperationException消息 " Collection was modified;

你必须这样做:

List<string> removals = new List<string>();
foreach (string s in theFinalList)
{
    //do stuff with (s);
    removals.Add(s);
}
foreach (string s in removals)
{
    theFinalList.Remove(s);
}

try

foreach (var line in theFinalList)
{
    string T = "";
    if (line.PartDescription != "")
        T = line.PartDescription + " " + line.PartNumber + "'n";
    else
        T = "N/A " + line.PartNumber + "'n";
    if (!(T.Contains("FID") || T.Contains("EXCLUDE"))
        lineList.Add (T);
}

我认为这更合乎逻辑

Regex exclude = new Regex("FID|EXCLUDE");
foreach (var line in theFinalList.Where(
 ln => !exclude.Match(ln.PartDescription).Success && 
       !exclude.Match(ln.PartNumber ).Success))){
    string partDescription = "N/A";
    if(!string.IsNullOrWhiteSpace(line.PartDescription)){
        partDescription = line.PartDescription;
    }
    lineList.Add(partDescription  + " " + line.PartNumber + "'n");
}

根据您的需要编辑regex(可能忽略大小写或多行,可能也编译),并随意将"'n"替换为Environment.NewLine

试试这个:

var excludingTexts = new [] { "FID", "EXCLUDE" }
lineList = lineList.Where(y => !excludingTexts.Any(x => line.PartDescription.Contains(x) || line.PartNumber.Contains(x))).ToList();

或者你可以重写为:

var excludingTexts = new [] { "FID", "EXCLUDE" }
List<string> lineList = (from line in theFinalList
                         where !excludingTexts.Any(x => line.PartDescription.Contains(x) || line.PartNumber.Contains(x))
                         select line.PartDescription != "" ? 
                                line.PartDescription + " " + line.PartNumber + "'n" : 
                                "N/A " + line.PartNumber + "'n"
                         ).ToList();