Nadeem Jamali
Nadeem Jamali

Reputation: 1423

Iterating result of Linq query

I am using following code to get result form a dataTable, but while using the resultant query in foreach loop, it throws an exception: "Unable to cast object of type 'System.Int64' to type 'System.String'". Please guide me where I have error in code.

var query = from detailRow in dtDetail.AsEnumerable() 
group detailRow by detailRow.Field<string>("Domain") into grouping
select new
{
   Domain = grouping.Key,
   Impressions = grouping.Count(),
   Clicks = 
   grouping.Sum(detailRow => int.Parse(detailRow.Field<string>("Clicks").ToString())),
   url = grouping.First<DataRow>()
}; 

foreach (var detailRowGroup in query)
{
  console.wirteline(detailRowGroup.Domain + detailRowGroup.Impressions + detailRowGroup.Clicks + detailRowGroup.url);

 }

Upvotes: 0

Views: 237

Answers (3)

Nadeem Jamali
Nadeem Jamali

Reputation: 1423

I resolved the problem, and found that I have had two mistakes in my code. Those were;
1. I used String on the place of Int64. By replacing String with Int64 the error resolved.
2. For DBNULL I used if condition.
Following is the code line;

Clicks = grouping.Sum(detailRow => Int64.Parse(detailRow.IsNull("Clicks") ? "0" : detailRow.Field<Int64>("Clicks").ToString())),

Thanks Steven and Steve Haigh.

Upvotes: 0

Steve
Steve

Reputation: 8511

Without knowing about your data it is hard to say, but I would guess that your Clicks column is numeric, so you would want the type parameter to be in long (64 bit int)?

I.e.

detailRow.Field<long>("Clicks")

maybe?

If that is true, then you can probably refactor your code to avoid the parsing too.

Upvotes: 1

Steven
Steven

Reputation: 172646

Your dtDetail DataTable contains a column, named Click that contains values of type Int64, while you are trying to retrieve it as an String. The problem is in the following line:

int.Parse(detailRow.Field<string>("Clicks").ToString())

Change it to:

int.Parse(detailRow.Field<Int64>("Clicks").ToString())

Upvotes: 1

Related Questions