1

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. I know there are rows before this query so it's got to be the LINQ query itself eliminating all of the rows. This is fine, but I need to be able to deal with this situation without it becoming an exception. Any ideas?

4

3 回答 3

1

您可能需要将其分解为两个语句:

DataTable dtCSVMultiSCOPassive = new DataTable();

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

if(query.Any())
{
    dtCSVMultiSCOPassive = query.CopyToDataTable();
}
于 2012-06-18T18:11:12.337 回答
0

您确定此语句不返回 null:

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

?

所以因为第一个条件tblGroupedMultiPassive.Count() > 0似乎是真的,我会尝试:

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

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

事实上,问题可能是几乎每个grp都只包含一个元素,因此查询返回 null 因为查询中的第二个条件grp.Count() > 1

于 2012-06-18T18:21:17.357 回答
0

我似乎grp.Count()总是 1,这表明您在第一个查询中具有product_id和的唯一组合。owner_org_id

顺便说一句,我认为这.SelectMany(grp => grp)完全是多余的。

于 2012-06-18T18:18:39.790 回答