组,排序与Linq元组列表

时间:2016-05-15 07:02:08

标签: c# linq sorting

我有这样的元组列表:

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***

然后插入每个&#34; somelabelForHeader&#34;和&#34;某种文字&#34;在一行。

就我而言:

     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)
                            {

                            }

                        }
                    }

使用上面的代码我可以对所有文本进行分组和连接但是如何在插入之前对第一行进行排序和提取?

2 个答案:

答案 0 :(得分: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));

关键是为标题(组的第一项)和文本部分(其余部分)创建单独的行。然后从那里,你可以生成新的计数器来创建你的最终元组。

答案 1 :(得分: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()));