在特定值后插入一行 - C#

时间:2016-08-11 19:36:34

标签: c# sql text reader

我有一个查询,它提供了超过500行,我根据特定的列名称命令它们,我将结果写入文本文件。 我想在每组的最后一行之后添加一个中断记录。 例如,我的查询结果是:

Name Address City State Zip   Phone   Break
AAA  BBB     CCC   SS   1234  555     
AAA  DDD     EEE   SS   1234  666
MMM  YYY     ZZZ   EE   4457  999
LLL  DDD     ooo   WW   7895  777

但我想添加额外的一行并添加"是"作为文本文件中的Break值为:

Name Address City State Zip   Phone   Break
AAA  BBB     CCC   SS   1234  555     
AAA  DDD     EEE   SS   1234  666
                                       YES
MMM  YYY     ZZZ   EE   4457  999
                                       YES
LLL  DDD     ooo   WW   7895  777
                                       YES

我的代码是:

string query = " select * from table order by name";
SqlDataReader reader;
string connStr = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
string strDelimiter = "\t";
string strDel = "\"";
string strFilePath = @"C:\" TextFile_" + DateTime.Now.ToString("yyyyMMdd") + ".txt";
StringBuilder sb = new StringBuilder();

using (SqlConnection conn = new SqlConnection(connStr))
{
    conn.Open();
    using (reader = new SqlCommand(query, conn).ExecuteReader())
    {

        for (int i = 0; i < reader.FieldCount; i++)
        {
            sb.Append(strDel);
            sb.Append(reader.GetName(i));
            sb.Append(strDel);
            if (i == reader.FieldCount - 1)
            {
                continue;
            }
            sb.Append(strDelimiter);
        }
        sb.Append(Environment.NewLine);
        if (reader.HasRows)
        {
            Object[] items = new Object[reader.FieldCount];

            while (reader.Read())
            {
                reader.GetValues(items);
                for (int i = 0; i < reader.FieldCount; i++)
                {
                    sb.Append(strDel);
                    sb.Append(reader.GetValue(i).ToString());
                    sb.Append(strDel);
                    if (i == reader.FieldCount - 1)
                    {
                        continue;
                    }
                    sb.Append(strDelimiter);
                }
                sb.Append(Environment.NewLine);

            }
        }
    }
    conn.Close();
    File.WriteAllText(strFilePath, sb.ToString());
}

1 个答案:

答案 0 :(得分:1)

var breakLine = new List<YourType> { new YourType { Break = "Yes"}};

var result = collection.GroupBy(item => item.Name)
                       .SelectMany(grouping => grouping.Union(breakLine))
                       .ToList();