我正在绑定一个选中的列表框,其中包含后续列表列表,但如果列表为空,我该如何管理它? 它会在ling语句中抛出异常,如果为null,我应该为checkedlist框设置什么
public List<dataObject> GetAllCustomItems(CategoryType currType, int mCategoryID)
{
List<dataObject> lst = null;
try
{
switch (currType)
{
case CategoryType.Dressing:
lst = (from xx in this.DressingItems
where xx.DressingInfo.CatID == mCategoryID
select new dataObject() {
ID = xx.DressingInfo.DressingID,
Name = xx.DressingInfo.Description,
Selected = xx.IsDefault
}).ToList();
break;
}
}
抛出异常
Value cannot be null.
Parameter name: source
答案 0 :(得分:1)
您确定this.DressingItems
不为空或空吗?
在LINQ查询之前检查:
if (this.DressingItems != null && this.DressingItems.Any()) {
lst = (from xx in this.DressingItems where...
}
如果lst
为空或空,请DressingItems
返回null。
修改 :(在评论后)
另外,请检查DressingInfo属性:
where xx.DressingInfo != null &&...
答案 1 :(得分:1)
如何在where子句
中首先检查DressingInfo是否为nullwhere xx.DressingInfo != null && xx.DressingInfo.CatID == mCategoryID
答案 2 :(得分:1)
var lst = (from xx in this.DressingItems
where xx.DressingInfo.CatID == mCategoryID
select new dataObject() {
ID = xx.DressingInfo.DressingID==null?0:xx.DressingInfo.DressingID,
Name = xx.DressingInfo.Description==null? "":xx.DressingInfo.Description,
Selected = xx.IsDefault
});
return IsNullThenNew<dataObject>(lst);
如果您不想将null返回给调用者,则可以通过下面的泛型方法返回至少空对象。
public static bool IsNullOrEmpty<T>(this IEnumerable<T> enumerable)
{
return enumerable == null || !enumerable.Any();
}
public static List<T> IsNullThenNew<T>(this IEnumerable<T> t)
{
if (!IsNullOrEmpty<T>(t))
{
return t.ToList();
}
else
{
Type genericListType = typeof(List<>);
Type listType = genericListType.MakeGenericType(t.GetType());
object listInstance = Activator.CreateInstance(listType);
return (List<T>)listInstance;
}//end if-else
}
答案 3 :(得分:0)
您可以更改List<dataObject> lst = null;
到List<dataObject> lst = new List<dataObject>
;
或者做这样的事情:
public List<dataObject> GetAllCustomItems(CategoryType currType, int mCategoryID)
{
try
{
switch (currType)
{
case CategoryType.Dressing:
List<dataObject> lst = (from xx in this.DressingItems
where xx.DressingInfo.CatID == mCategoryID
select new dataObject() {
ID = xx.DressingInfo.DressingID,
Name = xx.DressingInfo.Description,
Selected = xx.IsDefault
}).ToList();
break;
}
}