C# 格式化数据中的字符串

C# 格式化数据中的字符串,c#,linq,grouping,C#,Linq,Grouping,我有这样的数据: Name Update CC 12/31/2012 CS 12/31/2012 CI 04/30/2013 CR 04/30/2013 Dictionary<string, Designation> Designations = new Dictionary<string, Designation>(); select Update , Name from my_table order by Update

我有这样的数据:

Name    Update
CC      12/31/2012
CS      12/31/2012
CI      04/30/2013
CR      04/30/2013
Dictionary<string, Designation> Designations = new Dictionary<string, Designation>();
select Update , Name
from my_table
order by Update , Name
我需要这个输出:

Annual CC/CS Update: 12/31/2012
Annual CI/CR Update: 04/30/2013
Annual CC Update: 12/31/2012
Annual CI Update: 04/30/2013
但是,如果我的数据如下所示:

Name    Update
CC      12/31/2012
CI      04/30/2013
我需要这个输出:

Annual CC/CS Update: 12/31/2012
Annual CI/CR Update: 04/30/2013
Annual CC Update: 12/31/2012
Annual CI Update: 04/30/2013
不知道如何完成这项任务

顺便说一句,在ASP.Net MVC3中使用Razor

尝试以下操作:(注意AllianceDesignations是定义名称[])


@AllianceDesignations.GroupBy(x=>x.UpdateDue).Select(g=>String.Format(“年度{0}更新:{1}

”,String.Join(“/”,g.Select(y=>y.Name.ToArray()),g.Key))
这表明:

<div class="span6">
    System.Linq.Enumerable+WhereSelectEnumerableIterator`2[System.Linq.IGrouping`2[System.DateTime,MVC3MyPage.MyPageService.Designation],System.String]
</div>

System.Linq.Enumerable+其中SelectEnumerableInterator`2[System.Linq.iGroup`2[System.DateTime,MVC3MyPage.MyPageService.Designation],System.String]
另外,我已经把它们放在字典里,供其他类似的用途:

Name    Update
CC      12/31/2012
CS      12/31/2012
CI      04/30/2013
CR      04/30/2013
Dictionary<string, Designation> Designations = new Dictionary<string, Designation>();
select Update , Name
from my_table
order by Update , Name
字典名称=新字典();
您可以利用LINQ的。一旦检索到记录(假设您的类是Record),就可以使用LINQ扩展查询结果。代码可能并不完美,但它应该为您提供正确的想法

IEnumerable<Record> records = ....
var groups = records.GroupBy( f => f.Update );

foreach( IEnumerable<Record> r in groups ){
  Write( String.Join( "/", r.Select( rec => rec.Name ).ToArray() ), r.First().Update ) );
}
IEnumerable记录=。。。。
var groups=records.GroupBy(f=>f.Update);
foreach(组中的IEnumerable r){
Write(String.Join(“/”,r.Select(rec=>rec.Name.ToArray()),r.First().Update));
}
首先
更新
,然后是各组中的名称(未测试):


如果数据源是SQL,则可以尝试以下查询:

Name    Update
CC      12/31/2012
CS      12/31/2012
CI      04/30/2013
CR      04/30/2013
Dictionary<string, Designation> Designations = new Dictionary<string, Designation>();
select Update , Name
from my_table
order by Update , Name
现在您的数据已正确排序。你可以在没有linq的情况下阅读并分组,如下所示:

using ( SqlConnection conn = new SqlConnection( "some connect string" ) )
using ( SqlCommand    cmd  = conn.CreateCommand() )
{
  cmd.CommandText = @"select Update , Name from my_table order by Update , Name" ;
  cmd.CommandType = CommandType.Text ;

  using ( SqlDataReader reader = cmd.ExecuteReader() )
  {
    DateTime     prev_update = DateTime.MinValue ;
    List<string> names       = new List() ;
    while ( reader.Read() )
    {
      DateTime update = reader.GetDateTime( 0 ) ;
      String   name   = reader.GetString(   1 ) ;

      if ( update != prev_update )
      {
        if ( name.Length > 0 )
        {
          Console.WriteLine( "Annual {0} Update: {1}" , string.Join( "/" , names ) , prev_update ) ;
        }
        names.Clear() ;
        prev_update = update ;
      }

      names.Add( name ) ;

    }
    reader.Close() ;
  }
}
使用(SqlConnection conn=newsqlconnection(“某些连接字符串”))
使用(SqlCommand cmd=conn.CreateCommand())
{
cmd.CommandText=@“按更新、名称顺序从我的表格中选择更新、名称”;
cmd.CommandType=CommandType.Text;
使用(SqlDataReader=cmd.ExecuteReader())
{
DateTime prev_update=DateTime.MinValue;
列表名称=新列表();
while(reader.Read())
{
DateTime update=reader.GetDateTime(0);
字符串名称=reader.GetString(1);
如果(更新!=上一次更新)
{
如果(名称.长度>0)
{
WriteLine(“年度{0}更新:{1}”,string.Join(“/”,name),prev_Update);
}
name.Clear();
上一次更新=更新;
}
名称。添加(名称);
}
reader.Close();
}
}

不确定是否从文件中读取,确切的格式有点不清楚,但以下是一些代码,用于在使用指定格式从纯文本文件中读取时执行您想要的操作

//used to store converted data
Dictionary<string, string> data = new Dictionary<string, string>();

//open file, read line by line and store values as needed
using (TextReader tr = File.OpenText("test.txt"))
{
    //throw away header line
    string line = tr.ReadLine();
    while ((line = tr.ReadLine()) != null)
    {
        string[] values = line.Split((char[])null, StringSplitOptions.RemoveEmptyEntries);

        if (data.ContainsKey(values[1]))
            data[values[1]] += "/" + values[0];
        else
            data.Add(values[1], values[0]);
    }
}

//print results
foreach (string date in data.Keys)
    Console.WriteLine(String.Format("Annual {0} Update: {1}", data[date], date));
输出:

Annual CS/CI Update: 12/31/12
Annual CL/CS Update: 01/16/13

无法在注释中发布代码。但我所拥有的看起来并不正确。不要发表评论-编辑问题。你的数据是什么格式的?CSV?数据库?文件中的扁平字符串?textarea?AllianceDesignations字段作为指定数组从我的Web服务返回。指定有指定的字段(int)、名称(string)和UpdateDue(dateTime)。@MB34好的,现在我知道了数据结构的实际内容,我的技术应该以您想要的格式返回字符串列表。@MB34:您不需要使用数据库来使用LINQ。尝试此操作时,我得到一个错误在r.selects中“不能在声明前使用局部变量r”。如上所述,代码不是要作为工作解决方案进行复制和粘贴,而是作为传达解决方案理念的一种手段。请检查原始问题中的新数据。无法隐式将类型“System.Collections.Generic.IEnumerable”转换为“string[]“.@MB34对不起,我忘了。ToArray();最后,修复了。我刚刚将rowsOfData设置为可数。现在,我如何去掉指定中DateTime值的时间部分?每次尝试对该值使用格式时,都会出现显式转换错误。如果UpdateDue为null呢?它实际上是DateTime?可为null。只需将
指定ByDate.Key
更改为
指定ByDate.Key.ToSortDateString()