【问题标题】:Adding a line to a file在文件中添加一行
【发布时间】:2011-08-22 20:17:43
【问题描述】:

我有这个代码:

List<string> lineList = new List<string>();
in j = 0;
Dictionary<string, int> dictionary = new Dictionary<string, int>();

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

foreach (string word in lineList)
{
    if (dictionary.ContainsKey(word))
        dictionary[word]++;
    else
        dictionary[word] = 1;
}

var ordered = from k in dictionary.Keys
              orderby dictionary[k] descending
              select k;

foreach (string key in ordered)
{
    var splitKey = key.Split(' ');
    if (!splitKey[2].Contains("8"))
    {
        sw.WriteLine(string.Format("( {0} 0 1 1 0 0 0 0 \"\" \"\" \"\" 0 0 0 0 0 0 )", j);
        j++;
    }

    sw.WriteLine(string.Format("( {0} 0 1 1 0 0 0 0 \"{1}\" \"{2}\" \"\" {3} 0 0 0 0 0 )",
                               j, splitKey[0], splitKey[1], dictionary[key]));
    j++;
}

此输出的示例如下所示(假设所有line.TapeWidth包含“8”):

( 1 0 1 1 0 0 0 0 "2125R_1.0" "136380" "" 18 0 0 0 0 0 )
( 2 0 1 1 0 0 0 0 "2125R_1.0" "128587" "" 41 0 0 0 0 0 )
( 3 0 1 1 0 0 0 0 "2125R_1.0" "138409" "" 11 0 0 0 0 0 )
( 4 0 1 1 0 0 0 0 "2125R_1.0" "110984" "" 8 0 0 0 0 0 )
( 5 0 1 1 0 0 0 0 "3216R_1.3" "114441" "" 6 0 0 0 0 0 )

但是

我想改变它,所以如果!line.TapeWidth.Contains("8") 那么我想输出一个额外的行。假设包含"138409""114441" 的行都有一个TapeWidth,即不等于8。所以 NEW 输出看起来像这样:

( 1 0 1 1 0 0 0 0 "2125R_1.0" "136380" "" 18 0 0 0 0 0 )
( 2 0 1 1 0 0 0 0 "2125R_1.0" "128587" "" 41 0 0 0 0 0 )
( 3 0 1 1 0 0 0 0 "" "" "" 0 0 0 0 0 )
( 4 0 1 1 0 0 0 0 "2125R_1.0" "138409" "" 11 0 0 0 0 0 )
( 5 0 1 1 0 0 0 0 "2125R_1.0" "110984" "" 8 0 0 0 0 0 )
( 6 0 1 1 0 0 0 0 "" "" "" 0 0 0 0 0 )
( 7 0 1 1 0 0 0 0 "3216R_1.3" "114441" "" 6 0 0 0 0 0 )

所以

我正在尝试插入那个“空白”行BEFORE另一行被打印掉...

有人知道我该怎么做吗?

【问题讨论】:

  • 这似乎是一个简单的逻辑修改。如所问,您只是想让我们为您编写代码。没有尝试解决此处显示的问题。你试过什么?出了什么问题?
  • @Merlyn Morgan-Graham:我试过:else if (!(line.TapeWidth.Contains("8"))) { reutnr "" + "" + "\n"; } 在第一个 if/else 循环之间。

标签: c# list add contains


【解决方案1】:

这似乎是一种简单的方法,只需在打印该行之前检查条件即可。

foreach (string key in ordered)
{
    var splitKey = key.Split(' ');
    if (!splitKey[1].Contains("8")) {
        sw.WriteLine("( {0} 0 1 1 0 0 0 0 "" "" "" 0 0 0 0 0 )", j);
        j++;
    }
    sw.WriteLine(
        "( {0} 0 1 1 0 0 0 0 \"{1}\" \"{2}\" \"\" {3} 0 0 0 0 0 )",
        j, splitKey[0], splitKey[1], dictionary[key]);
    j++;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-05
    • 1970-01-01
    • 2011-01-03
    • 2017-10-14
    • 1970-01-01
    • 2021-06-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多