简体   繁体   English

C#-LINQ查询向表返回null并引发异常

[英]C# - LINQ query returns null to table and throws exception

I have a piece of code: 我有一段代码:

var tblGroupedMultiPassive = dtCSV.AsEnumerable()
                                  .Where(r => r.Field<String>("course_type_id") == "3")
                                  .GroupBy(r => new
                                  {
                                       product_id = r.Field<String>("product_id"),
                                       owner_org_id = r.Field<String>("owner_org_id"),
                                  });

if (tblGroupedMultiPassive.Count() > 0)
    dtCSVMultiSCOPassive = tblGroupedMultiPassive.Where(grp => grp.Count() > 1)
                                                 .SelectMany(grp => grp)
                                                 .CopyToDataTable();

Basically on the final statement where assigning to dtCSVMultiSCOPassive, it throws an exception for there being no rows. 基本上在分配给dtCSVMultiSCOPassive的最终声明中,它会抛出异常,因为没有行。 I know there are rows before this query so it's got to be the LINQ query itself eliminating all of the rows. 我知道在此查询之前有行,因此必须是LINQ查询本身,以消除所有行。 This is fine, but I need to be able to deal with this situation without it becoming an exception. 很好,但是我必须能够处理这种情况而不会成为例外。 Any ideas? 有任何想法吗?

You might need to break this into two statements: 您可能需要将此分为两个语句:

DataTable dtCSVMultiSCOPassive = new DataTable();

var query = tblGroupedMultiPassive.Where(grp => grp.Count() > 1).SelectMany(grp => grp);

if(query.Any())
{
    dtCSVMultiSCOPassive = query.CopyToDataTable();
}

I would appear that grp.Count() is always 1, which would indicate that you have unique combinations of product_id and owner_org_id in your first query. 我会发现grp.Count()始终为1,这表明您在第一个查询中具有product_idowner_org_id唯一组合。

BTW, I believe that .SelectMany(grp => grp) is completely redundant. 顺便说一句,我相信.SelectMany(grp => grp)是完全多余的。

Are you sure that this statement doesn't return null: 您确定此语句不会返回null:

dtCSVMultiSCOPassive = tblGroupedMultiPassive.Where(grp => grp.Count() > 1);

?

So because of the first conditional tblGroupedMultiPassive.Count() > 0 seems to be true I would try: 因此,由于第一个条件tblGroupedMultiPassive.Count() > 0似乎是正确的,所以我尝试:

if (tblGroupedMultiPassive.Count() > 0)
{
    dtCSVMultiSCOPassive = tblGroupedMultiPassive.Where(grp => grp.Count() > 1);

    if(dtCSVMultiSCOPassive != null)
       dtCSVMultiSCOPassive = dtCSVMultiSCOPassive.CopyToDataTable();
}

Infact the problem could be that almost every grp contains only one element so the query returns null becuase of the second conditional grp.Count() > 1 in your query. 实际上,问题可能在于几乎每个grp仅包含一个元素,因此查询返回空值,原因是查询中第二个条件grp.Count() > 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM