Linq Key仅包含每个重复的第一个

时间:2017-04-21 17:19:44

标签: c# excel linq dictionary

必须将列表转换为我的应用程序中的字典,但我得到一个错误,说“已经添加了具有相同键的项目”。 我需要第一个键和他的值

 Dictionary<string, string> cells = 
             (from cell in sheet.Cells["A1:J20"] 
             where cell.Start.Column == 1  && cell.Value != null
             select sheet.Cells[cell.Start.Row, 1, cell.Start.Row,9].Value)
             .Cast<object[,]>()
             .Distinct().ToDictionary(k => Convert.ToString(k[0, 2]), v => 
             Convert.ToString((v[0, 8])));

示例Excel:

  • kEY =&gt;的

  • Key1 =&gt; Value1

  • Key2 =&gt;值2
  • Key3 =&gt;值3
  • Key3 =&gt; VALUE4
  • Key3 =&gt;值5
  • Key6 =&gt; Value6
  • Key7 =&gt; Value7
  • Key23 =&gt; Value8

修改

 Dictionary<string, string> dict = new Dictionary<string, string>();

                    var cells = (from cell in sheet.Cells["A1:B16"]
                                 where cell.Start.Column == 1 && cell.Value != null
                                 select sheet.Cells[cell.Start.Row, cell.Start.Column, cell.Start.Row, 2].Value)
                                                        .Cast<object[,]>();

循环并添加到词典:

  foreach (var i in cells) {
                        if (dict.ContainsKey(Convert.ToString(i[0, 0])) == false)
                            dict.Add(Convert.ToString(i[0, 0]), Convert.ToString(i[0, 1]));
                        // dict.Distinct();

                    }

但我需要linq中的代码!!!

2 个答案:

答案 0 :(得分:0)

警告:未经测试的代码,我无法轻松创建测试环境:

Dictionary<string, string> cells = 
         (from cell in sheet.Cells["A1:J1"] 
         where cell.Value != null
         let key = sheet.Cells[cell.Start.Row, 3].Value.ToString()
         let val = sheet.Cells[cell.Start.Row, 9].Value.ToString()
         group val by key into vg
         select new { vg.Key, Val = vg.FirstOrDefault() })
         .ToDictionary(k => k.Key, v => v.Val);

另外,对我来说似乎有些问题进行了优化。

答案 1 :(得分:0)

我决定我的问题

Dictionary<string, string> dict = (from cell in sheet.Cells["A1:B34"]
                                 where cell.Start.Column == 1 && cell.Value != null
                                 select sheet.Cells[cell.Start.Row, cell.Start.Column, cell.Start.Row, 2].Value)
                                                        .Cast<object[,]>()
                                                        .GroupBy(k => Convert.ToString(k[0,0]))
                                                        .Select(k =>  k.First())
                                                        .ToDictionary(k => Convert.ToString(k[0, 0]), v => Convert.ToString(v[0, 1]))