【发布时间】:2017-09-18 19:17:48
【问题描述】:
必须在我的应用程序中将列表转换为字典,但我收到一条错误消息,提示“已添加具有相同键的项目”。 我需要第一把钥匙和他的价值
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 => 价值
Key1 => Value1
- Key2 => Value2
- Key3 => Value3
- Key3 => Value4
- Key3 => Value5
- Key6 => Value6
- 键7 => 值7
- Key23 => 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 中的代码!!!
【问题讨论】:
标签: c# excel linq dictionary