2016-05-15 96 views
1

元組的排序列表我的元組的名單如下:組,使用LINQ

List<Tuple<int,int, string>> list; 

並與填充的值:

1,200,"somelabelForHeaderA" 
2,200,"sometextA" 
3,200,"sometextA" 
4,222,"somelabelForHeaderB" 
5,222,"sometextB" 
6,222,"sometextB" 
7,300,"somelabelForHeaderC" 
8,300,"sometextC" 
9,401,"somelabelForHeaderD" 
10,401,"sometextD" 
11,401,"sometextD" 
12,401,"sometextD" 
現在

我想做的事是有點像這樣組:

1,200,"somelabelForHeaderA" <== ***Must Be Inserted in Column 1 Row 1*** 
2,200,"sometextA sometextA" <== ***Must Be Inserted in Column 2 Row 1*** 
3,222,"somelabelForHeaderB" <== ***Must Be Inserted in Column 1 Row 2*** 
4,222,"sometextB sometextB" <== ***Must Be Inserted in Column 2 Row 2*** 
5,300,"somelabelForHeaderC" <== ***Must Be Inserted in Column 1 Row 3*** 
6,300,"sometextC"   <== ***Must Be Inserted in Column 2 Row 3*** 
7,401,"somelabelForHeaderD" <== ***Must Be Inserted in Column 1 Row 4*** 
8,401,"sometextD sometextD sometextD" <== ***Insert in Column 2 Row 4*** 

然後在一行中插入每個「somelabelForHeader」和「sometext」。

這是據我去:

 var grouped = list.GroupBy(t => t.Item2, t => t.Item3) 
.Select(g => Tuple.Create(g.Key, string.Join("\n", g))); 

foreach (var groups in grouped) 
       { 
    using (SqlConnection sqlconnection = new SqlConnection(Connection_String)) 
       { 
        using (SqlCommand cmd = new SqlCommand()) 
        { 
         cmd.Connection = sqlconnection; 
         cmd.CommandType = CommandType.Text; 
         cmd.CommandText = query; 
         cmd.Parameters.AddWithValue("@a", groups.Item2); 
         cmd.Parameters.AddWithValue("@c", "???"); 
          try 
          { 
           sqlconnection.Open(); 
           cmd.ExecuteNonQuery(); 
          } 
          catch (SqlException ex) 
          { 

          } 

         } 
        } 

與上面的代碼我可以組和CONCAT所有文字,但如何可以排序和插入之前提取第一行?

回答

2

你可以這樣做:

var query = Items 
    .GroupBy(i => i.Item2, i => i.Item3) 
    .SelectMany(g => new[] 
    { 
     new { b = g.Key, c = g.First() }, 
     new { b = g.Key, c = String.Join(" ", g.Skip(1)) }, 
    }) 
    .Select((x, i) => Tuple.Create(i + 1, x.b, x.c)); 

的關鍵是頁眉(組的第一項)和文本部分(其餘)創建單獨的行。然後從那裏,你可以生成新的計數器來創建你的最終元組。

0

試試這個

var grouped = list.GroupBy(t => t.Item2) 
.Select(g => Tuple.Create(g.Key,g.Max(i=>i.Item3),g.Min(i=>i.Item3),g.Count()));