![](/img/trans.png)
[英]How to check that item in a list or enumerable template is not null in linq
[英]How to check in linq if the list is null?
我将以下重新绑定列表列表的行绑定到一个选中的列表框,但是如果列表为空,我应该如何管理它? 它在ling语句中引发异常,如果为null,则应为清单框设置什么
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
您确定this.DressingItems
不为null或为空吗?
在LINQ查询之前检查一下:
if (this.DressingItems != null && this.DressingItems.Any()) {
lst = (from xx in this.DressingItems where...
}
让lst
返回NULL DressingItems
为null或空。
编辑 :(在操作注释之后)
另外,检查DressingInfo属性:
where xx.DressingInfo != null &&...
如何在where子句中首先检查DressingInfo是否为null
where xx.DressingInfo != null && xx.DressingInfo.CatID == mCategoryID
我不认为是xx.DressingInfo对象问题,因为它会出来首先找不到对象引用,确定是xx.DressingInfo的值出现问题。 您可以尝试使用iif进行检查。
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
}
您可以更改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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.