根据现有的带元组字典创建带有组和计数的新字典

时间:2019-01-20 14:09:56

标签: c#

我有当前的词典testdict:

Dictionary<int, Tuple<int, string, string>> testdict

基本上是Dictionary<autoID, Tuple<ignore, "shortcode", "product_name">>

示例:

testdict.Add(1, new Tuple<int, string, string>(1, "555", "Light Blue"));
testdict.Add(2, new Tuple<int, string, string>(2, "122", "Majenta Red"));
testdict.Add(3, new Tuple<int, string, string>(2, "133", "Dark Yellow"));
testdict.Add(4, new Tuple<int, string, string>(1, "555", "Light Blue"));
testdict.Add(5, new Tuple<int, string, string>(1, "555", "Light Blue"));
testdict.Add(6, new Tuple<int, string, string>(2, "133", "Dark Yellow"));
testdict.Add(7, new Tuple<int, string, string>(2, "766", "Purple"));

我需要一个具有以下格式的新容器:

autoid, "shortcode" group, "product_name" group, "count"

简码和产品名称始终匹配,因此它们既可以分组也可以分组,然后选择第二个(例如第一个)。 可以忽略int键(仅用于创建订单)。 元组内部的int也将被忽略。

我需要的新容器的示例是:

Dictionary<int, Tuple<string, string, int>> newdict
newdict.Add(AutoID_Order, new Tuple<string, string, int>("shortcode", "product_name", count)); (structure)
newdict.Add(1, new Tuple<string, string, int>("555", "Light Blue", 3));
newdict.Add(2, new Tuple<string, string, int>("133", "Dark Yellow", 2));
newdict.Add(3, new Tuple<string, string, int>("122", "Majenta Red", 1));
newdict.Add(4, new Tuple<string, string, int>("766", "Purple", 1));

我该如何完成? Linq是可以接受的。

2 个答案:

答案 0 :(得分:1)

使用GroupBy,然后使用ToDictionary

testdict
  .GroupBy(x => new { x.Value.Item2, x.Value.Item3 })
  .Select((x, i) => new {
    i,
    ShortCode = x.Key.Item2,
    ProductName = x.Key.Item3,
    Count = x.Count(),
  })
  .ToDictionary(x => x.i, x => new Tuple<string, string, int>(x.ShortCode, x.ProductName, x.Count));

答案 1 :(得分:1)

int count=0;        
var z = testdict
        .GroupBy(x => new { x.Value.Item2, x.Value.Item3 })
        .ToDictionary(x => ++count, 
                      x => new Tuple<string, string, int>
                           (
                            x.Key.Item2, x.Key.Item3, x.Count()
                            ));