0
votes

have to cast a list to a dictionary in my app but im getting an error saying that "An item with the same key has already been added". I need first key and his value

 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])));

Example Excel:

  • kEY => Value

  • Key1 => Value1

  • Key2 => Value2
  • Key3 => Value3
  • Key3 => Value4
  • Key3 => Value5
  • Key6 => Value6
  • Key7 => Value7
  • Key23 => Value8

EDIT

 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[,]>();

cycle and add to dictionary:

  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();

                    }

but i need code in linq!!!

2

2 Answers

0
votes

Warning: untested code, I couldn't create a test environment easily:

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

Also, optimized out a lot that seemed questionable to me.

0
votes

I decide my problem

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