【发布时间】:2017-06-06 10:50:52
【问题描述】:
我有两个字典。一个包含 Excel 工作表中的列列表和已定义列的列表。我想知道工作表中是否存在定义的列。如果它们存在,那么它们将在选定的下拉列表中被选中。
在行 dropdownList.SelectedValue = selectedItem.First().Key; 我有时会收到错误消息序列不包含任何元素。我以为我已经编码了安全性。我忘记了什么?
...命令...
SetDataSource(import.ColumnList, import.DefColumnList, ddlSomeColumn, SomeEnum.Zipcode);
...然后调用方法...
private void SetDataSource(Dictionary<int, string> columnList, Dictionary<int, string> defColumnList, DropDownList dropdownList, SomeEnum item)
{
int index = (int)item;
dropdownList.BeginUpdate();
dropdownList.ValueMember = "Key";
dropdownList.DisplayMember = "Value";
dropdownList.DataSource = columnList;
if (defColumnList.ContainsKey(index) && defColumnList[index].Length > 0)
{
var selectedItem = columnList.Where(cl => cl.Value == defColumnList[index]);
if (selectedItem != null)
dropdownList.SelectedValue = selectedItem.First().Key;
}
dropdownList.EndUpdate();
}
【问题讨论】:
-
selectedItem.First()将在 selectedItem 为空时给出该错误。 -
当
columnList.Where(cl => cl.Value == defColumnList[index])产生一个空序列时会发生这种情况,然后您调用First()on。 -
SelectedItem将产生一系列项目。当您检查它是否不为空时,序列不为空并调用First将导致此错误。最好将您的检查更改为类似 var selectedItem = columnList.Where(cl => cl.Value == defColumnList[index]); if (selectedItem != null && selectedItem.Any()) dropdownList.SelectedValue = selectedItem.First().Key; -
我知道当 First() 为空时,您会收到错误消息。但我一直在寻找这样的东西:if (selectedItem.Any())。它有效......
-
我现在明白了:我的问题的标题是错误的......我已经改变了这个。
标签: c# linq dictionary