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?

2
  • 1
    Is that the entire query? Where's your grouping statement? Are you certain that there are cases where your grouping included more than one row? Commented Jun 18, 2012 at 18:07
  • that is the part throwing the exception. I will edit the post and include the rest of the code. Commented Jun 18, 2012 at 18:10

3 Answers 3

1

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();
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

BTW, I believe that .SelectMany(grp => grp) is completely redundant.

Comments

0

Are you sure that this statement doesn't return null:

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

?

So because of the first conditional tblGroupedMultiPassive.Count() > 0 seems to be true I would try:

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.